maximillianx

Windows-Update.vbs

May 13th, 2017
1,162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VBScript 50.48 KB | None | 0 0
  1. strScriptVer = "2.8 - Rob Dunn @ http://community.spiceworks.com"
  2. '~~[author]~~
  3. 'Rob Dunn
  4. 'with some additional improvements made by the WSUS and Spiceworks community
  5. ' - thank you!
  6. '~~[/author]~~
  7. '
  8. '~~[ContactInfo]~~
  9. 'https://community.spiceworks.com/people/robdunn
  10. '~~[/ContactInfo]~~
  11. '
  12. '~~[website]~~
  13. 'For future versions and support:
  14. 'https://community.spiceworks.com/scripts/show/82
  15. '~~[/website]~~
  16. '
  17. '~~[scriptType]~~
  18. 'vbscript
  19. '~~[/scriptType]~~
  20.  
  21. '~~[subType]~~
  22. 'SystemAdministration
  23. '~~[/subType]~~
  24.  
  25. '~~[keywords]~~
  26. 'wsus, windows, updates, hotfixes, email, windowsupdate, microsoft, wua, sus,
  27. '~~[/keywords]~~
  28. '
  29. '~~[usage]~~
  30. '****Install updates silently, email you a logfile, then restart the computer****  
  31. 'updatehf.vbs action:install mode:silent email:[email protected] restart:1
  32. '
  33. '****Install specific update silently, email you a logfile, then restart the computer****  
  34. 'updatehf.vbs action:install mode:silent email:[email protected] updateid:80BC2B42-A953-4096-8595-130E9A9C9FB9 restart:1
  35. '
  36. 'Note: To look up updateids, go to the KB ID on Microsoft's Update Catalog page, like this for KB4012212:
  37. ' http://www.catalog.update.microsoft.com/Search.aspx?q=KB4012212
  38. '
  39. 'Click the update you are interested in, a pop-up window should appear.  Look at the URL.  The UpdateID is in the address:
  40. 'http://www.catalog.update.microsoft.com/ScopedViewInline.aspx?updateid=652eea96-c2e8-4548-8f9a-40964e5e6a74
  41. '
  42. '****Detect missing updates, email you a logfile, then do nothing (no restart)****
  43. 'updatehf.vbs action:detect mode:verbose email:[email protected] restart:0
  44. '
  45. '****Prompt user to let them decide whether or not to install updates, email
  46. ' you a logfile, prompt user for restart****
  47. 'updatehf.vbs action:prompt mode:verbose email:[email protected] restart:1
  48. '
  49. '****Install updates silently, email you a logfile, then shutdown the computer
  50. ' if a reboot is pending****
  51. 'updatehf.vbs action:install mode:silent email:[email protected] restart:2
  52. '
  53. '****Install updates silently, email you a logfile, then shutdown the computer
  54. ' no matter if a reboot is pending or not****
  55. 'updatehf.vbs action:install mode:silent email:[email protected] restart:2 force:1
  56. '
  57. '****Detect missing updates or pending reboot silently, email you a logfile, then
  58. ' restart if there is a pending reboot****
  59. 'updatehf.vbs action:detect mode:silent email:[email protected] restart:1
  60. '
  61. '****Detect missing updates or pending reboot silently, email you a logfile, then
  62. ' restart no matter if there is a pending reboot****
  63. 'updatehf.vbs action:detect mode:silent email:[email protected] restart:1 force:1
  64. '
  65. '~~[/usage]~~
  66. 'This script (the core was pulled from Microsoft's website - thank
  67. ' you!) will tell the WU agent to 'detectnow', download and install
  68. ' missing windows updates as compared to it's update server. Works for
  69. ' WSUS and regular Windows Update site.
  70. '
  71. 'This will now reboot the computer if specified after the udpates have
  72. ' been applied (or if there is a reboot pending from a previous update session).
  73. '
  74. 'NOTE: If there are a LOT of downloads to pull, the status window (or log)
  75. ' will say "Downloading" for that entire time. I'm not sure how to get
  76. ' a download progress of each update...maybe someone can help me with that.
  77. '
  78. 'Note on command-line switches: If you don't specify a switch (for
  79. ' example, 'email:') the corresponding variable defined in the script will
  80. ' provide the needed information (command-line switches take precedence).
  81. '
  82. 'Why I put this script together:
  83. 'Our desktop deployment technicians needed a script that would pull
  84. ' updates immediately and install, even if the update configuration is set
  85. ' for 'download only' via Group Policy.
  86. '
  87. 'We have some computers that are sometimes logged on or not (but
  88. ' they run services that must be running almost constantly), and are never rebooted.
  89. '
  90. 'The user ignores the 'you have new updates available' message, so updates are
  91. ' never installed. This script will let you install the updates, and then it
  92. ' tells the WUA to present the 'restart' message - which more users are apt to
  93. ' respond to.
  94. '
  95. 'After the script runs, it will email a recipient the resulting logfile that is
  96. ' produced.
  97. '
  98. '*******************************************************************************
  99. 'You need to edit the following variables:
  100. '
  101. 'strMailFrom - arbitrary reply-to address
  102. 'strMailto - email address you want the report to mail to (this is for manual
  103. ' mode
  104. ' - or if the command-line switch isn't specified).
  105. 'strSMTPServer - the IP address of the email server you are sending the reports
  106. ' through.
  107. '
  108. '*******************************************************************************
  109. 'Optional variables:
  110. 'Silent - 0 = verbose, 1 = silent (no windows or visible information)
  111. 'Intdebug - 0 = off, 1 = 1 (see some variables that are being passed)
  112. 'strAction - prompt|install|detect. Prompt gives users opportunity to install
  113. ' updates or not, install just installs them, detect updates the WU collection
  114. ' and downloads the updates (but does not install them) - useful if you want to
  115. ' have the computer refresh its stats to the stat server but not install the
  116. ' updates.
  117. 'blnEmail - 0 = off|1 = on. If set to 0, the script will not email a log file.
  118. ' If you specify an email address in the command-line, this will force the
  119. ' script to switch blnEmail to '1'.
  120. 'strRestart - 0 = Do nothing|1 = restart|2 = shutdown. Command-switch 'restart:'
  121. ' supercedes this variable.
  122. '
  123. '*******************************************************************************
  124. 'Command line switches:
  125. '
  126. 'action: prompt|install|detect
  127. 'updateid: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  128. 'mode: silent|verbose
  129. 'restart: 0 (do nothing)| 1 (restart) | 2 (shutdown)
  130. 'force: 0 (do not enforce restart action - this is optional, by default it is
  131. ' set to 0) | 1 (enforce restart action).
  132. 'SMTPServer: x.x.x.x or hostname; overrides strSMTPServer above.
  133. 'emailsubject: "this is a subject" Overrides default subject. Server name is appended to this text. Use quotes if spaces exist.
  134. 'emailifallok: 0|1, where 0 = dont send email if server up to date and no
  135. ' reboot pending, and 1 = always send email
  136. 'fulldnsname: 0|1, where 0 = use server name only in subject, and 1 = use full
  137. ' dns name in email subject
  138. 'authtype: cdoAnonymous|cdoNTLM|cdoBasic - authentication type for SMTP (default
  139. ' is 'cdoAnonymous', no creds needed)
  140. 'authID: SMTP authentication ID
  141. 'authPassword: SMTP authentication password
  142. '
  143. '
  144. 'Make sure you rename this file with .vbs
  145. '*******************************************************************************
  146. Dim objArgs,strArgs
  147. Dim l
  148. Set objArgs = Wscript.Arguments
  149.  
  150. 'Get all arguments
  151. For Each strArg in objArgs
  152.   strArguments = strArguments & " " & strArg
  153. Next
  154.  
  155. 'Handle UAC
  156. If Not WScript.Arguments.Named.Exists("elevate") Then
  157.   CreateObject("Shell.Application").ShellExecute WScript.FullName _
  158.     , WScript.ScriptFullName & " /elevate" & " " & strArguments, "", "runas", 1
  159.   WScript.Quit
  160. End If
  161.  
  162. Const HKEY_CURRENT_USER             = &H80000001
  163. Const HKEY_LOCAL_MACHINE            = &H80000002
  164. Const ForAppending                  = 8
  165. Const ForWriting                    = 2
  166. Const ForReading                    = 1
  167. Const cdoAnonymous                  = 0 'Do not authenticate
  168. Const cdoBasic                      = 1 'basic (clear-text) authentication
  169. Const cdoNTLM                       = 2 'NTLM
  170. Const cdoSendUsingMethod            = "http://schemas.microsoft.com/cdo/configuration/sendusing", _
  171.             cdoSendUsingPort        = 2, _
  172.             cdoSMTPServer           = "http://schemas.microsoft.com/cdo/configuration/smtpserver", _
  173.             cdoSMTPServerport       = "http://schemas.microsoft.com/cdo/configuration/smtpserverport", _
  174.             cdoSMTPconnectiontimeout = "http://schemas.microsoft.com/cdo/configuration/Connectiontimeout"
  175.  
  176. 'Web address to refer users for unhandled error codes
  177. strAddr = "https://support.microsoft.com/en-us/kb/938205"
  178.  
  179. On Error Resume Next
  180.  
  181. 'below variables for progress indicators
  182. Dim objShell, objProcessEnv, objSystemEnv, objNet, objFso, objSwitches
  183. Dim query, item, acounter, blnExtendedWMI, blnProcessEvents
  184. Dim dlgBarWidth, dlgBarHeight, dlgBarTop, dlgBarLeft, dlgProgBarWidth, dlgProgBarHeight
  185. Dim dlgProgBarTop, dlgProgBarLeft
  186. Dim dlgBar, dlgProgBar, wdBar, objPBar, objBar, blnSearchWildcard
  187. Dim blnProgressMode, blnDebugMode, dbgTitle
  188. Dim dbgToolBar, dbgStatusBar, dbgResizable
  189. Dim IE, objDIV, objDBG, strMyDocPath, strSubFolder, strTempFile, f1, ts, File2Load, objFlash
  190. Dim dbgWidth, dbgHeight, dbgLeft, dbgTop, dbgVisible
  191. 'above variables for progress indicators
  192. Dim blnRebootRequired
  193.  
  194. Dim strAction, regWSUSServer, ws, wshshell, wshsysenv, strMessage, strFrom
  195.  
  196. Dim strRestart, silenttext, restarttext, blnCallRestart, blnInstall, blnPrompt, strStatus
  197. Dim blnIgnoreError, blnCScript, strLocaleDelim
  198.  
  199. Set WshShell = WScript.CreateObject("WScript.Shell")
  200. Set WshSysEnv = WshShell.Environment("PROCESS")
  201. Set ws = wscript.CreateObject("Scripting.FileSystemObject")
  202. Set objADInfo = CreateObject("ADSystemInfo")
  203.  
  204. 'Try to pick up computername via AD'
  205. strComputer1 = objADInfo.ComputerName
  206.  
  207. 'As a backup, use the environment strings to pick up the computer
  208. ' name.
  209. strComputer = wshShell.ExpandEnvironmentStrings("%Computername%")
  210.  
  211. strUser = WshSysEnv("username")
  212. strDomain = WshSysEnv("userdomain")
  213.  
  214. 'Get computer OU
  215. strOU = "Computer OU: Not detected"
  216.  
  217. Set objComputer = GetObject("LDAP://" & strComputer1)
  218. If objComputer.Parent <> "" Then  
  219.     strOU = "Computer OU: " & replace(objComputer.Parent,"LDAP://","")
  220. End If
  221.  
  222. If InStr(ucase(WScript.FullName),"CSCRIPT.EXE") Then
  223.     blnCScript = TRUE
  224. Else
  225.     blnCScript = FALSE
  226. End If
  227.  
  228. blnCloseIE = true
  229.  
  230. '*******************************************************************************
  231. ' User variables
  232. '*******************************************************************************
  233. 'Turn on debugging.  This will show some of the variables that are being passed
  234. ' while the script executes.
  235. Intdebug = 0          
  236.  
  237. 'How long between the time that the script is finished and the IE window stays
  238. ' on the screen.  Set to '0' if you don't want the status window to close
  239. ' automatically.
  240. intSleep = 2000
  241.  
  242. 'Whether or not the user will see the status window.
  243. ' Possible options are:
  244. '0 = verbose, progress indicator, status window, etc.
  245. '1 = silent, no progress indicators.  Everything occurs in the background
  246. Silent = 1
  247.      
  248. 'The location of the logfile (this is the file that will be parsed
  249. ' and the contents will be sent via email.                      
  250. logfile = WshSysEnv("TEMP") & "\" & "vbswsus-status.log"
  251.                                      
  252. 'arbitrary email address - reply-to
  253. strMailFrom = "[email protected]"
  254.  
  255. 'who are you mailing to?  Input mode only.  Command-line parameters take
  256. ' precedence
  257. strMailto = "[email protected]"
  258.  
  259. 'set SMTP email server address here
  260. strSMTPServer = "x.x.x.x"
  261.  
  262. 'set SMTP email server port (default is 25)
  263. iSMTPServerPort = 25
  264.  
  265. 'The computer name will follow this text when the script completes.
  266. strSubject = "[WSUS Update Script] - WSUS Update log file from"
  267.  
  268. 'Deliminator in above strWUAgentVersion - some locales might have "," instead
  269. ' (Non English) - leave as "." if you aren't sure.
  270. strLocaleDelim = "."
  271.  
  272. 'default option for manual run of the script.  Possible options are:
  273. ' prompt - (user is prompted to install)
  274. ' install - updates will download and install
  275. ' detect - updates will download but not install                                      
  276. strAction = "install"
  277.  
  278. 'Turns email function on/off.  If an email address is specified in the
  279. ' command-line arguments, then this will automatically turn on ('1').
  280. ' 0 = off, don't email
  281. ' 1 = on, email using default address defined in the var 'strMailto' above.
  282. blnEmail = 1
  283.  
  284. 'strEmailIfAllOK Determines if email always sent or only if updates or reboot
  285. ' needed.
  286. ' 0 = off, don't send email if no updates needed and no reboot needed
  287. ' 1 = on always send email
  288. strEmailIfAllOK = 0
  289.  
  290. 'strFullDNSName Determines if the email subject contains the full dns name of
  291. ' the server or just the computer name.
  292. ' 0 = off, just use computer name
  293. ' 1 = on,  use full dns name
  294. strFullDNSName = 0
  295.  
  296. 'tells the script to prompt the user (if running in verbose mode) to input the
  297. ' email address of the recipient they wish to send the script log file to.  The
  298. ' default value in the field is determined by the strMailto variable above.
  299. '
  300. 'This only appears if no command-line arguments are given.  
  301. '0 = do not prompt the user to type in an email address
  302. '1 = prompt user to type in email address to send the log to.
  303. promptemail = 0
  304.  
  305. 'Tells the computer what to do after script execution if the script detects that
  306. ' there is a pending reboot.
  307. '
  308. 'Command-prompt supercedes this option.
  309. '0 = do nothing
  310. '1 = reboot
  311. '2 = shutdown
  312. strRestart = 0
  313.  
  314. 'Try to force the script to work through any errors.  Since some are recoverable
  315. ' this might be an option for troubleshooting.  Default is 'true'
  316. blnIgnoreError = true
  317.  
  318. 'sets font for display status dialog and sent formatted logfile
  319. strFontStyle = "arial"
  320.  
  321. 'set your SMTP server authentication type.  
  322. ' Possible values:cdoAnonymous|cdoBasic|cdoNTLM
  323. ' You do not need to configure an id/pass combo with cdoAnonymous
  324. strAuthType = "cdoAnonymous"
  325.  
  326. 'SMTP authentication ID
  327. strAuthID = ""
  328.  
  329. 'Password for the ID
  330. strAuthPassword = ""
  331.  
  332. '*******************************************************************************
  333. 'End of User variables
  334. '*******************************************************************************
  335.  
  336. 'writelog("Arguments: " & wscript.arguments)
  337. writelog("Log file used: " & logfile)
  338. If intdebug = 1 then wscript.echo "Objargs.count = " & objArgs.count
  339.  
  340. If objArgs.Count > 0 Then
  341. For I = 0 to objArgs.Count - 1
  342.   If objArgs.Count > 0 Then
  343.     if instr(LCase(objargs(i)),"action:") Then
  344.       strArrAction = split(objargs(i),":")
  345.       strAction = strArrAction(1)
  346.       if intdebug = 1 then wscript.echo strAction
  347.       'wscript.quit
  348.    ElseIf instr(LCase(objargs(i)),"mode:") Then
  349.       strArrMode = split(objargs(i),":")
  350.       silent = strArrMode(1)
  351.       If lcase(silent) = "silent" then
  352.         silent = 1
  353.       Elseif lcase(silent) = "verbose" then
  354.         silent = 0
  355.         blnCloseIE = true
  356.       Else
  357.         strMsg = "Invalid mode switch: " & silent & ".  Now aborting."
  358.         'Call ErrorHandler("Command Switches",strMsg,"true")
  359.      End If
  360.       Silenttext = strArrMode(1)
  361.     ElseIf instr(LCase(objargs(i)),"email:") Then
  362.        strArrEmail = split(objargs(i),":")
  363.        strMailto = strArrEmail(1)
  364.        blnEmail = 1
  365.         ElseIf instr(LCase(objargs(i)),"logfile:") Then
  366.        strArrLogfile = split(objargs(i),"logfile:")
  367.        LogFile = strArrLogFile(1)
  368.     ElseIf InStr(LCase(objargs(i)),"restart:") Then
  369.         strArrAction = split(objargs(i),":")
  370.         strRestart = strArrAction(1)
  371.     ElseIf InStr(LCase(objargs(i)),"force:") Then
  372.         strArrForceAction = split(objargs(i),":")
  373.         strForceaction = strArrForceAction(1)
  374.     ElseIf InStr(LCase(objargs(i)),"smtpserver:") Then
  375.         strArrSMTPServer = split(objargs(i),":")
  376.         strSMTPServer = strArrSMTPServer(1)
  377.     ElseIf InStr(LCase(objargs(i)),"emailifallok:") Then
  378.         strArrEmailIfAllOK = split(objargs(i),":")
  379.         strEmailIfAllOK = strArrEmailIfAllOK(1)
  380.     ElseIf InStr(LCase(objargs(i)),"fulldnsname:") Then
  381.         strArrFullDNSName = split(objargs(i),":")
  382.         strFullDNSName = strArrFullDNSName(1)
  383.     ElseIf InStr(LCase(objargs(i)),"emailsubject:") Then
  384.         strArrSubject = split(objargs(i),":")
  385.         strSubject = strArrSubject(1)
  386.     ElseIf InStr(LCase(objargs(i)),"authtype:") Then
  387.         strArrAuthType = split(objargs(i),":")
  388.         strAuthType = strArrAuthType(1)
  389.     ElseIf InStr(LCase(objargs(i)),"authid:") Then
  390.         strArrAuthID = split(objargs(i),":")
  391.         strAuthID = strArrAuthID(1)
  392.     ElseIf InStr(LCase(objargs(i)),"authpassword:") Then
  393.         strArrAuthPassword = split(objargs(i),":")
  394.         strAuthPassword = strArrAuthPassword(1)  
  395.     ElseIf Instr(LCase(objargs(i)),"updateid:") Then
  396.         strArrKBID = split(objargs(i),":")
  397.         strKBID = strArrKBID(1)
  398.    End If
  399.   End If
  400. Next
  401. Else
  402.       'strAction = "prompt"
  403.      If blnEmail = 1 and silent = 0 and promptemail = 1 Then strMailto = InputBox("Input the email address you would like the " _
  404.        & "Windows Update agent log sent to:","Email WU Agent logfile to recipient",strMailto)
  405.       If strMailto = "" Then wscript.quit
  406. End If
  407.  
  408. Set l = ws.OpenTextFile (logfile, ForWriting, True)
  409. l.writeline "------------------------------------------------------------------"
  410. l.writeline "WU force update VBScript" & vbcrlf & Now & vbcrlf & "Computer: " & strComputer
  411. l.writeline "Script version: " & strScriptVer
  412. l.writeline strOU
  413.  
  414. l.writeline "Executed by: " & strDomain & "\" & strUser
  415. l.writeline "Command arguments: " & strArguments
  416. l.writeline "------------------------------------------------------------------"
  417.     'Call WMI query to collect parameters for reboot action
  418.     Set OpSysSet = GetObject("winmgmts:{(Shutdown)}//" & strComputer & "/root/cimv2").ExecQuery("select caption,OSArchitecture,ServicePackMajorVersion from Win32_OperatingSystem"_
  419.      & " where Primary=true")
  420.         For each item in OpSysSet
  421.             strOS = item.caption
  422.             strOSArchitecture = item.OSArchitecture
  423.             strSP = item.ServicePackMajorVersion
  424.         Next
  425.        
  426.         writelog("Operating System: " & strOS)
  427.         writelog("Service Pack: " & strSP)
  428.         writelog("OS Architecture: " & strOSArchitecture)
  429.  
  430. If blnEmail = 1 then
  431.     writelog("SMTP Authentication type specified: " & strAuthType)
  432.     If lcase(strAuthType) <> "cdoanonymous" Then
  433.       If strAuthType = "" Then
  434.         strAuthType = "cdoanonymous"
  435.       Else
  436.         writelog("SMTP Auth User ID: " & sAuthID)
  437.    
  438.         If SMTPUserID = "" then
  439.           writelog("No SMTP user ID was specified, even though SMTP Authentication was configured for " & strAuthType & ".  Attempting to switch to anonymous authentication...")
  440.           strAuthType = "cdoanonymous"
  441.           If strAuthPassword <> "" then writelog("You have specified a SMTP password, but no user ID has been configured for authentication.  Check the INI file (" & sINI & ") again and re-run the script.")
  442.         Else
  443.           if strAuthPassword = "" then writelog("You have specified a SMTP user ID, but have not specified a password.  Switching to anonymous authentication.")
  444.           strAuthType = "cdoanonymous"
  445.         End if
  446.         If strAuthPassword <> "" then writelog("SMTP password configured, but hidden...")
  447.    
  448.       End If
  449.     End If
  450. End If
  451.  
  452. 'Call checkupdateagent
  453.  
  454. Select Case silent
  455.   Case 0
  456.     silenttext = "Verbose"
  457.   Case 1
  458.     silenttext = "Silent"
  459.   Case Else
  460. End Select
  461.  
  462. If strForceaction = 1 Then
  463.     strForceText = " (enforce action)"
  464. Else
  465.     strForceText = " (only if action is pending)"
  466. End If
  467.  
  468. Select Case strRestart
  469.   Case 0
  470.     restarttext = "Do nothing"
  471.   Case 1
  472.     restarttext = "Restart"
  473.   Case 2
  474.     restarttext = "Shut down"
  475.   Case Else
  476. End Select
  477.  
  478. restarttext = restarttext & strForceText
  479.  
  480. writelog("Script action is set to: " & strAction)
  481. writelog("Verbose/Silent mode is set to: " & silenttext)
  482. writelog("Restart action is set to: " & restarttext)
  483.  
  484. Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
  485.  strComputer & "\root\default:StdRegProv")
  486. strKeyPath = "SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate"
  487. strValueName = "WUServer"
  488. oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,regWSUSServer
  489. writelog("Checking local WU settings...")
  490.  
  491. Call GetAUSchedule()
  492.  
  493. If regWSUSServer then
  494. Else
  495.   regWSUSServer = "Microsoft Windows Update"
  496. End If
  497.  
  498. writelog("Update Server: " & regWSUSServer)
  499.  
  500. writelog("HTTP Status: " & URLGet(regWSUSServer))
  501. strValueName = "TargetGroup"
  502.  
  503. oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,regTargetGroup
  504. if regTargetGroup <> "" then
  505.   writelog("Target Group: " & regTargetGroup)
  506. Else
  507.   writelog("Target Group: Not specified")
  508. End If
  509.  
  510. Set autoUpdateClient = CreateObject("Microsoft.Update.AutoUpdate")
  511. Set updateInfo = autoUpdateClient.Settings
  512.  
  513. Select Case updateInfo.notificationlevel
  514.     Case 0
  515.       writelog("WUA mode: WU agent is not configured.")
  516.     Case 1
  517.       writelog("WUA mode: WU agent is disabled.")
  518.     Case 2
  519.       writelog("WUA mode: Users are prompted to approve updates prior to installing")
  520.     Case 3
  521.       writelog("WUA mode Updates are downloaded automatically, and users are prompted to install.")
  522.     Case 4
  523.       writelog("WUA mode: Updates are downloaded and installed automatically at a predetermined time.")
  524.     Case Else
  525. End Select
  526.  
  527.  
  528. fstyle = "calibri,tahoma,arial,verdana"
  529. bgcolor1 = "aliceblue"
  530. fformat = "<font face='" & fstyle & "'>"
  531.  
  532. 'set some IE status indicator variables...
  533. blnDebugMode = True
  534. blnProcessEvents = True
  535. blnSearchWildcard = False
  536. blnProgressMode = True
  537.  
  538. On Error Resume Next
  539.  
  540. Set updateSession = CreateObject("Microsoft.Update.Session")
  541. Set updateSearcher = updateSession.CreateupdateSearcher()
  542.  
  543. writelog("Instantiating Searcher")
  544. If strKBID <> "" Then
  545.     writelog("Searching for specific UpdateID: " & strKBID)
  546.     strQuery = "UpdateID='" & strKBID & "'"
  547. Else
  548.     writelog("Checking for all approved updates according to WU agent")
  549.     strQuery = "IsAssigned=1 and IsHidden=0 and IsInstalled=0 and Type='Software'"
  550. End If
  551.  
  552. writelog("Searcher query: " & strQuery)
  553. Set searchResult = updateSearcher.Search(strQuery)
  554.  
  555.  
  556. 'Handle some common errors here
  557. If cstr(err.number) <> 0 Then
  558.   If cstr(err.number) = "-2147012744" Then
  559.     strMsg = "ERROR_HTTP_INVALID_SERVER_RESPONSE - The server response could not be parsed." & vbcrlf & vbcrlf & "Actual error was: " _
  560.       & " - Error [" & cstr(err.number) & "] - '" & err.description & "'"
  561.     blnFatal = true
  562.   ElseIf Cstr(err.number) = "-2145107952" Then
  563.     strMsg = "WU_E_PT_EXCEEDED_MAX_SERVER_TRIPS The number of round trips to the server exceeded the maximum limit. " _
  564.      & "Stop/Restart service or reboot the machine if you see this error frequently. " _
  565.      & vbcrlf & vbcrlf & "Actual error was [" & err.number & "] - " & chr(34) _
  566.       & err.description & chr(34)
  567.     blnFatal = true
  568.   ElseIf CStr(err.number) = "-2145107924" Then
  569.     strMsg = "WU_E_PT_WINHTTP_NAME_NOT_RESOLVED - Winhttp SendRequest/ReceiveResponse failed with 0x2ee7 error. Either the proxy " _
  570.      & "server or target server name can not be resolved. Corresponding to ERROR_WINHTTP_NAME_NOT_RESOLVED. " _
  571.      & "Stop/Restart service or reboot the machine if you see this error frequently. " _
  572.      & vbcrlf & vbcrlf & "Actual error was [" & err.number & "] - " & chr(34) _
  573.       & err.description & chr(34)
  574.     blnFatal = false
  575.   ElseIf cstr(err.number) <> 0 and cstr(err.number) = "-2147012867" Then
  576.     strMsg = "ERROR_INTERNET_CANNOT_CONNECT - The attempt to connect to the server failed." & vbcrlf _
  577.       & vbcrlf & "Actual error was [" & err.number & "] - " & chr(34) _
  578.       & err.description & chr(34)
  579.     blnFatal = true
  580.   ElseIf CStr(err.number) = "-2145107941" Then
  581.     strMsg = "SUS_E_PT_HTTP_STATUS_PROXY_AUTH_REQ - Http status 407 - proxy authentication required" & vbcrlf & vbcrlf & "Actual " _
  582.      & "error was [" & err.number & "]" & chr(34) & err.description & chr(34)
  583.   ElseIf CStr(err.number) = "-2145124309" Then
  584.     strMsg = "WU_E_LEGACYSERVER - The Sus server we are talking to is a Legacy Sus Server (Sus Server 1.0)" _
  585.      & vbcrlf & vbcrlf & "Actual error was [" & err.number & "] - " & chr(34) & err.description & chr(34)
  586.     blnFatal = true
  587.   ElseIf CStr(err.number) = "7" Then
  588.     strMsg = "Out of memory - In most cases, this error will be resolved by rebooting the client." _
  589.      & VbCrLf & VbCrLf & "Actual error was [" & err.number & "] - " & chr(34) & err.description & chr(34)
  590.     blnFatal = True
  591.   Else
  592.     If err.description = "" Then
  593.         errdescription = "No error description given"
  594.     Else
  595.         errdescription = err.description
  596.     End If
  597.     If blnIgnoreError = false Then
  598.         blnFatal = true
  599.         strScriptAbort = vbcrlf & vbcrlf & "Script will now abort. - if you want to force the script to continue, change the 'blnIgnoreError' variable " _
  600.          & "to the value 'true'"
  601.     Else
  602.         strScriptabort = vbcrlf & vbcrlf & "Script will attempt to continue."
  603.     End If
  604.    
  605.     strMsg = "Error - [" & err.number & "] - " & chr(34) & errdescription & chr(34) & "." & vbcrlf & vbcrlf _
  606.      & "This error is undefined in the script, but you can refer to " & strAddr & " to look up the error number." _
  607.      & strScriptAbort
  608.      strMsgHTML = replace(strMsg,strAddr,"<a href='" & strAddr & "'>" & strAddr & "</a>")
  609.     If silent = 0 Then objdiv.innerhtml = replace(strMsgHTML,"vbcrlf","<br>")
  610.    End If
  611.  
  612.   Call ErrorHandler("UpdateSearcher",strMsg,blnFatal)
  613. End If
  614. 'ssManagedServer
  615.  
  616. If silent = 0 then
  617.   writelog("Calling IE Status Window")
  618.     on error goto 0
  619.     Call IEStatus
  620. End If
  621.  
  622. Call CheckPendingStatus("beginning")
  623.  
  624. strMsg = "Refreshing WUA client information..."
  625. if silent = 0 then objdiv.innerhtml = strMsg
  626.  
  627. 'cause WU agent to detect
  628. on error resume next
  629. autoUpdateClient.detectnow()
  630. if err.number <> 0 then call ErrorHandler("WUA refresh",err.number & " - " & err.description,false)
  631. err.clear
  632. on error goto 0
  633.  
  634. strMsg = "WUA mode: <font color='navy'>" & strACtion & "</font><br>WU Server: " & regWSUSServer _
  635.  & "<br>Target Group: " & regTargetGroup & "<br><br>List of applicable items on the machine: <br>"
  636. writelog("WUA mode: " & straction)
  637. writelog("WU Server: " & regWSUSServer)
  638.  
  639. writelog(regWSUSServer & "/iuident.cab Status: " & URLGet(regWSUSServer & "/iuident.cab"))
  640.  
  641. If silent = 0 then objdiv.innerhtml = strMsg
  642. If strAction <> "detect" Then
  643.     writelog("Searching for missing or updates not yet applied...")
  644.     writelog("Missing " & searchResult.Updates.Count & " update(s).")
  645. End If
  646. on error resume next
  647.  
  648. For i = 0 To searchResult.Updates.Count-1
  649.     Set update = searchResult.Updates.Item(i)
  650.     'if update.MsrcSeverity = "Important" then wscript.echo "This item (" & update.Title & ") is " & update.MsrcSeverity
  651.     strSearchResultUpdates = strSearchResultUpdates & update.Title & "<br>"
  652.     Set objCategories = searchResult.Updates.Item(i).Categories
  653.     writelog("Missing: " & searchResult.Updates.Item(i))
  654. Next
  655.  
  656.  
  657. if err.number <> 0 then
  658.     writelog("An error has occured while instantiating search results.  Error " & err.number & " - " & err.description _
  659.         & ".  Check the " & wshShell.ExpandEnvironmentStrings("%windir%") & "\windowsupdate.log file for further information.")
  660.  
  661.     blnFatal = false
  662. End IF
  663.  
  664.     if silent = 0 then objdiv.innerhtml = strMsg & strsearchResultUpdates
  665.    
  666. If searchResult.Updates.Count = 0 Then
  667.    
  668.   strMsg = fformat & "There are no further updates needed for your PC at this time."
  669.    
  670.     if silent = 0 then objdiv.innerhtml = strMsg & "<br><br><a href='file:///" & logfile & "'>View log file</a>"
  671.  
  672.   writelog(replace(strMsg,fformat,""))
  673.   writelog("Events saved to '" & logfile & "'")
  674.  
  675.   Call EndOfScript
  676.   wscript.quit
  677. End If
  678.  
  679.  
  680. If intdebug = 1 then WScript.Echo vbCRLF & "Creating collection of updates to download:"
  681. If strAction <> "detect" Then writelog("Creating a catalog of needed updates")
  682.  
  683. writelog("********** Cataloging updates **********")
  684.  
  685. Set updatesToDownload = CreateObject("Microsoft.Update.UpdateColl")
  686.  
  687. For I = 0 to searchResult.Updates.Count-1
  688.     Set update = searchResult.Updates.Item(I)
  689.     if update.MsrcSeverity <> "" then MsrcSeverity = "(" & update.MsrcSeverity & ") "
  690.     strUpdates = strUpdates & MsrcSeverity & "- " & update.Title & "<br>"
  691.     writelog("Cataloged: " & MsrcSeverity & update.Title)
  692.     If Not update.EulaAccepted Then update.AcceptEula
  693.     updatesToDownload.Add(update)
  694. Next
  695.  
  696. If silent = 0 then objdiv.innerhtml = ""
  697. strMsg = fformat & "This PC requires updates from the configured Update Server" _
  698.  & " (" & regWSUSServer & ").  "
  699. If strAction <> "detect" Then strmsg = strmsg & "<br><br> Downloading needed updates.  Please stand by..."
  700.  
  701. if silent = 0 then objdiv.innerhtml = strMsg
  702. writelog(replace(replace(strMsg,fformat,""),"<br>",""))
  703.  
  704. If strAction = "detect" Then
  705.    
  706. Else
  707.    
  708.     Set downloader = updateSession.CreateUpdateDownloader()
  709.     on error resume next
  710.     downloader.Updates = updatesToDownload
  711.     writelog("********** Downloading updates **********")
  712.  
  713.     downloader.Download()
  714.  
  715.     if err.number <> 0 then
  716.         writelog("Error " & err.number & " has occured.  Error description: " & err.description)
  717.     End if
  718.  
  719.     strUpdates = ""
  720.     strMsg = ""
  721.     if silent = 0 then objdiv.innerhtml = ""
  722.     strMsg = fformat & "List of downloaded updates: <br><br>"
  723.     if silent = 0 then objdiv.innerhtml = strMsg
  724.    
  725.     For I = 0 To searchResult.Updates.Count-1
  726.         Set update = searchResult.Updates.Item(I)
  727.         If update.IsDownloaded Then
  728.            strDownloadedUpdates = strDownloadedUpdates & update.Title & "<br>"
  729.         End If
  730.         On Error GoTo 0
  731.         'writelog(searchResult.Updates.Item(i))
  732.         writelog("Downloaded: " & update.Title)
  733.         if silent = 0 then objdiv.innerhtml = strMsg & strDownloadedUpdates
  734.     Next
  735.    
  736.     Set updatesToInstall = CreateObject("Microsoft.Update.UpdateColl")
  737.    
  738.     strUpdates = ""
  739.     strMsg = ""
  740.     if silent = 0 then objdiv.innerhtml = ""
  741.     strMsg = fformat & "Creating collection of updates needed to install:<br><br>"
  742.  
  743.     If silent = 0 then objdiv.innerhtml = strMsg
  744.     writelog("********** Adding updates to collection **********")
  745.  
  746.     For I = 0 To searchResult.Updates.Count-1
  747.         set update = searchResult.Updates.Item(I)
  748.         If update.IsDownloaded = true Then
  749.            strUpdates = strUpdates & update.Title & "<br>"
  750.            updatesToInstall.Add(update)
  751.         End If
  752.            writelog("Adding to collection: " & update.Title)
  753.            if silent = 0 then objdiv.innerhtml = strMsg & strUpdates   
  754.     Next
  755. End If
  756.  
  757.  
  758. If lcase(strAction) = "prompt" Then
  759.   strMsg = "The Windows Update Agent has detected that this computer is missing updates from the " _
  760.    & " configured server (" & regWSUSServer & ")." & vbcrlf & vbcrlf & "Would you like to install updates now?"
  761.   strResult = MsgBox(strMsg,36,"Install now?")
  762.   strUpdates = ""
  763.   writelog(strMsg & " [Response: " & strResult & "]")
  764.   strMsg = ""
  765.   If silent = 0 then objdiv.innerhtml = ""
  766.  
  767. ElseIf strAction = "detect" Then
  768.   strMsg = fformat & "Windows Update Agent has finished detecting needed updates."
  769.   writelog(replace(strMsg,fformat,""))
  770.  
  771.   if silent = 0 then objdiv.innerhtml = strMsg & "<br><br>"
  772.  
  773.   Call EndOfScript
  774.   wscript.quit
  775. ElseIf strAction = "install" Then
  776.   strResult = 6
  777. End If
  778.  
  779. strUpdates = ""
  780. if silent = 0 then objdiv.innerhtml = ""
  781.  
  782. If strResult = 7 Then
  783.   strMsg = strMsg & "<br>User cancelled installation.  This window can be closed."
  784.   writelog(replace(strMsg,"<br>",""))
  785.  
  786.   if silent = 0 then objdiv.innerhtml = strMsg
  787.  
  788.     WScript.Quit
  789. ElseIf strResult = 6 Then
  790.   strMsg = ""
  791.   Set installer = updateSession.CreateUpdateInstaller()
  792.   installer.AllowSourcePrompts = False
  793.   on error resume next
  794.  
  795.   installer.ForceQuiet = True
  796.  
  797.   strMsg = fformat & "Installing updates... <br><br>"
  798.   writelog(replace(replace(strMsg,fformat,""),"<br>",""))
  799.  
  800. ' If silent = 0 Then objdiv.innerhtml = strMsg & "<br>&bull; " & update.title
  801.  
  802.  If err.number <> 0 Then
  803.     writelog("Error " & err.number & " has occured.  Error description: " & err.description)
  804.  End if
  805.  
  806.     installer.Updates = updatesToInstall
  807.    
  808.     writelog("********** Installing updates **********")
  809.    
  810.     blnInstall = true
  811.    
  812.     on error resume next   
  813.     Set installationResult = installer.Install()
  814.    
  815.     If Silent = 0 then objdiv.innerhtml = strMsg
  816.    
  817.     writelog(replace(replace(strMsg,fformat,""),"<br>",""))
  818.    
  819.     If err.number <> 0 then
  820.         'strMsg = "Error installing updates... Actual error was " & err.number & " - " & err.description & "."
  821.         'writelog(strmsg)
  822.         if silent = 0 then objdiv.innerhtml = strMsg
  823.     End If
  824.  
  825.     'Output results of install
  826.     strMsg = fformat & "Installation Result: " & installationResult.ResultCode & "<br><br>" _
  827.      & "Reboot Required: " & installationResult.RebootRequired & "<br><br>" _
  828.      & "Listing of updates and individual installation results: <br>"
  829.  
  830.      For i = 0 to updatesToInstall.Count - 1
  831.         If installationResult.GetUpdateResult(i).ResultCode = 2 Then
  832.             strResult = "Installed"
  833.         ElseIf installationResult.GetUpdateResult(i).ResultCode = 1 Then
  834.             strResult = "In progress"
  835.         ElseIf installationResult.GetUpdateResult(i).ResultCode = 3 Then
  836.             strResult = "Error"
  837.         ElseIf installationResult.GetUpdateResult(i).ResultCode = 4 Then
  838.             strResult = "Failed"
  839.         ElseIf installationResult.GetUpdateResult(i).ResultCode = 5 Then
  840.             strResult = "Aborted"          
  841.         End If
  842.         writelog(strResult & ": " & updatesToInstall.Item(i).Title)
  843.         strUpdates = strUpdates & strResult & ": " & updatesToInstall.Item(i).Title & "<br>"
  844.     Next
  845.     if silent = 0 then objdiv.innerhtml = strMsg & strUpdates
  846. End If     
  847.  
  848. Call EndOfScript
  849. wscript.quit
  850.  
  851. '*******************************************************************************
  852. 'Function Writelog
  853. '*******************************************************************************
  854. Function WriteLog(strMsg)
  855. l.writeline "[" & time & "] - " & strMsg
  856. ' Output to screen if cscript.exe
  857. If blnCScript Then WScript.Echo "[" & time & "] " & strMsg
  858. End Function
  859.  
  860. '*******************************************************************************
  861. 'Function IE Status
  862. '*******************************************************************************
  863. Function IEStatus
  864.  
  865. 'added by Rob - IE status indicator code
  866. If blnProgressMode Then
  867.     If blnDebugMode Then
  868.         dbgTitle = "Windows Update Script " & strScriptVer
  869.     Else
  870.         dbgTitle = "Windows Update Script " & strScriptVer
  871.     End If 
  872.     dbgToolBar = False
  873.     dbgStatusBar = False
  874.     If blnDebugMode Then
  875.         dbgResizable = True
  876.     Else
  877.         dbgResizable = False
  878.     End If
  879.     dbgWidth = 500
  880.     dbgHeight = 320
  881.  
  882.  on error resume next
  883.  
  884.     'get video resolution via WMI
  885.    Set vids = GetObject("WinMgmts:").instancesof("Win32_VideoController")
  886.         for each v in vids
  887.                 HorScreen = v.CurrentHorizontalResolution
  888.                 VerScreen = v.CurrentVerticalResolution
  889.         next
  890.     If err.number <> 0 then
  891.         dbgLeft = 100
  892.         dbgTop = 200
  893.         err.clear
  894.     Else
  895.         HorScreen = 800
  896.         VerScreen = 600
  897.         dbgLeft = (HorScreen * .5) - (dbgWidth/2)
  898.         dbgTop = (VerScreen * .5) - (dbgHeight/2)
  899.     End if
  900.  
  901.  
  902.     dbgLeft = (HorScreen * .5) - (dbgWidth/2)
  903.     dbgTop = (VerScreen * .5) - (dbgHeight/2)
  904.     dbgVisible = True
  905.     dlgBarWidth = 380
  906.     dlgBarHeight = 23
  907.     dlgBarTop = 5
  908.     dlgBarLeft = 82
  909.     dlgProgBarWidth = 0
  910.     dlgProgBarHeight = 18
  911.     dlgProgBarTop = 82
  912.     dlgProgBarLeft = 50
  913.     dlgBar = "left: " & dlgBarLeft & "; top: " & dlgBarTop & "; width: " & dlgBarWidth _
  914.      & "; height: " & dlgBarHeight & ";"
  915.     dlgProgBar = "left: " & dlgProgBarLeft & "; top: " & dlgProgBarTop & "; width: " _
  916.      & dlgProgBarWidth & "; height: " & dlgProgBarHeight & ";"
  917.     wdBar = 1 * dlgBarWidth
  918. End If
  919.  
  920. If blnProgressMode Then
  921.   ' in case people has used the search bar in IE, turn it off
  922.  ' Thank you Torgeir!
  923.  Set IEtmp = CreateObject("InternetExplorer.Application")
  924.   IEtmp.ShowBrowserBar "{30D02401-6A81-11D0-8274-00C04FD5AE38}", False
  925.   IEtmp.Quit
  926.  
  927.   Set IEtmp = Nothing
  928.   WScript.Sleep 1000
  929.    
  930.   Set IE = CreateObject("InternetExplorer.Application")
  931.     'strScriptVer = "version would go here"
  932.  
  933.     strTempFile = WshSysEnv("TEMP") & "\progress.htm"
  934.     ws.CreateTextFile (strTempFile)
  935.         Set f1 = ws.GetFile(strTempFile)
  936.         Set ts = f1.OpenAsTextStream(2, True)
  937.         ts.WriteLine("<!-- saved from url=(0014)about:internet -->")
  938.         ts.WriteLine("<html><head><title>" & dbgTitle & " " & strScriptVer & " </title>")
  939.         ts.WriteLine("<style>.errortext {color:red}")
  940.         ts.WriteLine(".hightext {color:blue}</style>")
  941.     ts.WriteLine("</head>")
  942.     ts.WriteLine(strHDRCode & " <br><strong><font size='2' color='" & fcolor & "' face='" & fstyle & "'>" _
  943.         & "&nbsp Running Windows Update Client...<br>" _
  944.         & "&nbsp &nbsp<br>")
  945.     ts.WriteLine("<center><table width='100%' bgcolor='" & bgcolor1 & "'><tr><td>")
  946.     If blnDebugMode Then
  947.         ts.WriteLine("<body bgcolor ='" & stsBGColor & "' scroll='yes' topmargin='0' leftmargin='0'"_
  948.         & " style='font-family: " & fstyle & "; font-size: 0.6em color: #000000;"_
  949.         & " font-weight: bold; text-align: left'><center><font face=" & fstyle & ">"_
  950.         & " <font size='0.8em'> <hr color='blue'>")
  951.     Else
  952.         ts.WriteLine("<body bgcolor = '" & stsBGColor & "' scroll='no' topmargin='0' leftmargin='0' "_
  953.         & " style='font-family: " & fstyle & "; font-size: 0.6em color: #000000;"_
  954.         & " font-weight: bold; text-align: left'><center><font face=" & fstyle & ">"_
  955.         & " <font size='0.8em'> <hr color='blue'>")
  956.     End If
  957.     ts.WriteLine("<div id='ProgObject' align='left'align='left' style='width: 450px;height: 140px;overflow:scroll'></div><hr color='blue'>")           
  958.     If blnDebugMode Then
  959.         ts.WriteLine("<div id='ProgDebug' align='left'></div>")
  960.     End If
  961.  
  962.     ts.WriteLine("<script LANGUAGE='JavaScript1.2'>")
  963.     ts.WriteLine("<!-- Begin")
  964.     ts.WriteLine("function initArray() {")
  965.     ts.WriteLine("this.length = initArray.arguments.length;")
  966.     ts.WriteLine("for (var i = 0; i < this.length; i++) {")
  967.     ts.WriteLine("this[i] = initArray.arguments[i];")
  968.     ts.WriteLine("   }")
  969.     ts.WriteLine("}")
  970.     ts.WriteLine("var ctext = ' ';")
  971.     ts.WriteLine("var speed = 1000;")
  972.     ts.WriteLine("var x = 0;")
  973.     ts.WriteLine("var color = new initArray(")
  974.     ts.WriteLine("'red',")
  975.     ts.WriteLine("'blue'")
  976.     ts.WriteLine(");")
  977.     ts.WriteLine("document.write('<div id=" & Chr(34) & "ProgFlash" & Chr(34) & ">"_
  978.      & "<center>'+ctext+'</center></div>');")
  979.     ts.WriteLine("function chcolor(){")
  980.     ts.WriteLine("document.all.ProgFlash.style.color = color[x];")
  981.     ts.WriteLine("(x < color.length-1) ? x++ : x = 0;")
  982.     ts.WriteLine("}")
  983.     ts.WriteLine("setInterval('chcolor()',1000);")
  984.     ts.WriteLine("// End -->")
  985.     ts.WriteLine("</script>")
  986.     ts.WriteLine("<div id='ProgBarId' align='left'></div>")
  987.     ts.WriteLine("</font></center>")
  988.     ts.WriteLine("</tr></td>")
  989.     ts.WriteLine("</table></center>")
  990.     ts.WriteLine("</body></html>")
  991.     ts.Close
  992.     fctSetupIE(strTempFile)
  993.     Set objDIV = IE.Document.All("ProgObject")
  994.     If blnDebugMode Then
  995.         Set objDBG = IE.Document.All("ProgDebug")
  996.     End If
  997.     Set objFlash = IE.Document.All("ProgFlash")
  998.     Set objPBar = IE.Document.All("ProgBarId")
  999.     Set objBar = IE.Document
  1000. End If
  1001. If silent = 1 Then
  1002. 'remarked by Rob Set logwindow = ie.document.all.text1
  1003. End If
  1004. End Function
  1005. '*******************************************************************************'*  Name:   fctSetupIE
  1006. '*  Function:   Setup an IE windows of 540 x 200 to display
  1007. '*  progress information.
  1008. '*******************************************************************************
  1009. Sub fctSetupIE(File2Load)
  1010.     IE.Navigate File2Load
  1011.     IE.ToolBar = dbgToolBar
  1012.     IE.StatusBar = dbgStatusBar
  1013.     IE.Resizable = dbgResizable
  1014.     Do
  1015.     Loop While IE.Busy
  1016.     IE.Width = dbgWidth
  1017.     IE.Height = dbgHeight
  1018.     IE.Left = dbgLeft
  1019.     IE.Top = dbgTop
  1020.     IE.Visible = dbgVisible
  1021.     wshshell.AppActivate("Microsoft Internet Explorer")
  1022. End Sub
  1023.  
  1024. Sub GetAUSchedule()
  1025. Set objAutoUpdate = CreateObject("Microsoft.Update.AutoUpdate")
  1026. Set objSettings = objAutoUpdate.Settings
  1027.  
  1028. Select Case objSettings.ScheduledInstallationDay
  1029.     Case 0
  1030.         strDay = "every day"
  1031.     Case 1
  1032.         strDay = "sunday"
  1033.     Case 2
  1034.         strDay = "monday"
  1035.     Case 3
  1036.         strDay = "tuesday"
  1037.     Case 4
  1038.         strDay = "wednesday"
  1039.     Case 5
  1040.         strDay = "thursday"
  1041.     Case 6
  1042.         strDay = "friday"
  1043.     Case 7
  1044.         strDay = "saturday"
  1045.     Case Else
  1046.         strDay = "The scheduled installation day is could not be determined."
  1047. End Select
  1048.  
  1049. If objSettings.ScheduledInstallationTime = 0 Then
  1050.     strScheduledTime = "12:00 AM"
  1051. ElseIf objSettings.ScheduledInstallationTime = 12 Then
  1052.     strScheduledTime = "12:00 PM"
  1053. Else
  1054.     If objSettings.ScheduledInstallationTime > 12 Then
  1055.         intScheduledTime = objSettings.ScheduledInstallationTime - 12
  1056.         strScheduledTime = intScheduledTime & ":00 PM"
  1057.     Else
  1058.         strScheduledTime = objSettings.ScheduledInstallationTime & ":00 AM"
  1059.     End If
  1060.     'strTime = "Scheduled installation time: " & strScheduledTime
  1061. End If
  1062.  
  1063. writelog("Windows update agent is scheduled to run on " & strDay & " at " & strScheduledTime)
  1064. End Sub
  1065.  
  1066. '*******************************************************************************
  1067. 'Function URLGet - Check to see if web page is active
  1068. '
  1069. 'Thanks to http://www.sebsworld.net/information/?page=VBScript-URL
  1070. '*******************************************************************************
  1071. Function URLGet(URL)
  1072.         on error goto 0
  1073.         '   Set Http = CreateObject("WinHttp.WinHttpRequest.5.1")
  1074.         '   Set Http = CreateObject("WinHttp.WinHttpRequest.5")
  1075.         '   Set Http = CreateObject("WinHttp.WinHttpRequest")
  1076.         '   Set Http = CreateObject("Msxml2.ServerXMLHTTP.6.0")
  1077.         '   Set Http = CreateObject("MSXML2.ServerXMLHTTP")
  1078.             Set Http = CreateObject("MSXML2.XMLHTTP")
  1079.         '   Set Http = CreateObject("Microsoft.XMLHTTP")
  1080.        
  1081.        
  1082.         Http.Open "HEAD",URL,False
  1083.         'const SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS = 13056
  1084.         'Http.setOption 2, SXH_SERVER_CERT_IGNORE_ALL_SERVER_ERRORS
  1085.        
  1086.         Http.Send
  1087.        
  1088.         'pagestatus = Http.status
  1089.         If Http.status <> "403" and Http.status <> "200" Then
  1090.             URLGet = "(ERROR):" & Http.status
  1091.         Else
  1092.             'URLGet = Http.ResponseBody
  1093.             'URLGet = Http.responseText
  1094.             URLGet = "OK " & Http.status
  1095.         End if
  1096.        
  1097.        
  1098. End Function
  1099.  
  1100. Function URLPost(URL,FormData,Boundary)
  1101.   Set Http = CreateObject("Microsoft.XMLHTTP")
  1102.   Http.Open "POST",URL,True
  1103. '  Http.setRequestHeader "Content-Type","multipart/form-data; boundary="& Boundary
  1104.  Http.send FormData
  1105.   for n = 1 to 9
  1106.     If Http.readyState = 4 then exit for
  1107.     ' Http.waitForResponse 1
  1108.    b = shell.popup("Getting page",1,"Message")
  1109.   next
  1110.   If Http.readyState <> 4 then
  1111.     URLPost = "Failed"
  1112.   else
  1113.     URLPost = Http.responseText
  1114.   end if
  1115. End Function
  1116.  
  1117. '*******************************************************************************
  1118. 'Function SendMail - email the warning file
  1119. '*******************************************************************************
  1120. Function SendMail(strFrom,strTo,strSubject,strMessage)
  1121. Dim iMsg, iConf, Flds
  1122.  
  1123. writelog("Calling sendmail routine")
  1124. writelog("To: " & strMailto)
  1125. writelog("From: " & strMailFrom)
  1126. writelog("Subject: " & strSubject)
  1127. writelog("SMTP Server: " & strSMTPServer)
  1128.  
  1129. 'If silent = 0 Then objdiv.innerhtml = "<font face=" & strFontStyle & " color=" & strFontColor2& ">" _
  1130. ' & "sending mail to " & strMailTo & "...</font><br>"
  1131.  
  1132. '//  Create the CDO connections.
  1133. Set iMsg = CreateObject("CDO.Message")
  1134. Set iConf = CreateObject("CDO.Configuration")
  1135. Set Flds = iConf.Fields
  1136.  
  1137. If lcase(strAuthType) <> "cdoanonymous" Then
  1138.   'Type of authentication, NONE, Basic (Base64 encoded), NTLM
  1139.  iMsg.Configuration.Fields.Item _
  1140. ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = strAuthType
  1141.  
  1142.   'Your UserID on the SMTP server
  1143.  iMsg.Configuration.Fields.Item _
  1144. ("http://schemas.microsoft.com/cdo/configuration/sendusername") = strAuthID
  1145.  
  1146.   'Your password on the SMTP server
  1147.  iMsg.Configuration.Fields.Item _
  1148. ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = strAuthPassword
  1149.  
  1150. End if
  1151.  
  1152. '// SMTP server configuration.
  1153. With Flds
  1154.     .Item(cdoSendUsingMethod) = cdoSendUsingPort
  1155.     .Item(cdoSMTPServer) = strSMTPServer
  1156.     .Item(cdoSMTPServerPort) = iSMTPServerPort
  1157.     .Item(cdoSMTPconnectiontimeout) = 60
  1158.     .Update
  1159. End With
  1160. 'l.close
  1161.  
  1162. Dim r
  1163. Set r = ws.OpenTextFile (logfile, ForReading, False, TristateUseDefault)
  1164. strMessage = "<font face='" & strFontStyle & "' size='2'>" & r.readall & "</font>"
  1165.  
  1166. '//  Set the message properties.
  1167. With iMsg
  1168.     Set .Configuration = iConf
  1169.         .To       = strMailTo
  1170.         .From     = strMailFrom
  1171.         .Subject  = strSubject
  1172.         '.TextBody = strMessage
  1173. End With
  1174.  
  1175. 'iMsg.AddAttachment wsuslog
  1176. iMsg.HTMLBody = replace(strMessage,vbnewline,"<br>")
  1177. '//  Send the message.
  1178. on error resume next
  1179.  
  1180. iMsg.Send ' send the message.
  1181. Set iMsg = nothing
  1182.  
  1183. If CStr(err.number) <> 0 Then
  1184.     strMsg = "Problem sending mail to " & strSMTPServer & "." _
  1185.    & "Error [" & err.number & "]: " & err.description & "<br>"
  1186.  
  1187.   Call ErrorHandler("Sendmail function",replace(strMsg,"<br>",""),"false")
  1188.   'writelog(strMsg)
  1189.  strStatus = strMsg
  1190.   If silent = 0 Then objdiv.innerhtml = strStatus
  1191. Else
  1192.   strStatus = "Connected successfully to email server " & strSMTPServer
  1193.   writelog(strStatus)
  1194.     strStatus = strStatus & "<br><br><font face=" & strFontStyle & " color=" & strFontColor2& ">" _
  1195.  & "sent email to " & strMailTo & "...</font><br><BR>" _
  1196.      & "Script complete.<br><br><a href='file:///" & logfile & "'>View log file</a>"
  1197.     If silent = 0 Then objdiv.innerhtml = strStatus
  1198. End If
  1199.  
  1200. 'cause WU agent to detect
  1201. autoUpdateClient.detectnow()
  1202. blnEmail = 0
  1203.  
  1204. End Function
  1205. '*******************************************************************************'Function RestartAction
  1206. 'Sub to perform a restart action against the computer
  1207. '*******************************************************************************
  1208. Function RestartAction
  1209.   If silent = 0 Then objdiv.innerhtml = strStatus & "<br> Now performing post-execute action (" & restarttext & ")."
  1210.   wscript.sleep 4000
  1211.   writelog("Processing PostExecuteAction")
  1212.     'On Error GoTo 0
  1213.     Dim OpSysSet, OpSys
  1214.     'writelog("Computer: " & strComputer & vbcrlf & "Post-execution action: " & strRestart)
  1215.  
  1216.     'On Error Resume Next
  1217.    
  1218.     'Call WMI query to collect parameters for reboot action
  1219.     Set OpSysSet = GetObject("winmgmts:{(Shutdown)}//" & strComputer & "/root/cimv2").ExecQuery("select * from Win32_OperatingSystem"_
  1220.      & " where Primary=true")
  1221.      
  1222.     If CStr(err.number) <> 0 Then
  1223.       strMsg = "There was an error while attempting to connect to " & strComputer & "." & vbcrlf & vbcrlf _
  1224.          & "The actual error was: " & err.description
  1225.         writelog(strMsg)
  1226.         blnFatal = true
  1227.         Call ErrorHandler("WMI Connect",strMsg,blnFatal)
  1228.     End If
  1229.  
  1230.     Const EWX_LOGOFF = 0
  1231.     Const EWX_SHUTDOWN = 1
  1232.     Const EWX_REBOOT = 2
  1233.     Const EWX_FORCE = 4
  1234.     Const EWX_POWEROFF = 8
  1235.    
  1236.     'set PC to reboot
  1237.     If strRestart = 1 Then
  1238.  
  1239.         For each OpSys in OpSysSet
  1240.             opSys.win32shutdown EWX_REBOOT + EWX_FORCE
  1241.         Next
  1242.  
  1243.     'set PC to shutdown
  1244.     ElseIf strRestart = 2 Then
  1245.                
  1246.         For each OpSys in OpSysSet
  1247.             opSys.win32shutdown EWX_POWEROFF + EWX_FORCE
  1248.         Next
  1249.  
  1250.   'Do nothing...
  1251.  ElseIf strRestart = "0" Then
  1252.                    
  1253. End If
  1254.  
  1255.  
  1256. End Function
  1257.  
  1258. '*******************************************************************************
  1259. 'Sub ErrorHandler
  1260. 'Sub to help display/log any errors that occur
  1261. '*******************************************************************************
  1262. Sub ErrorHandler(strSource,strMsg,blnFatal)
  1263.     'Set theError = RemoteScript.Error
  1264.  
  1265.         If silent = 0 then wscript.echo "Source: " & strSource & " - " & strMsg
  1266.         writelog(strMsg)
  1267.         If blnFatal = true then wscript.quit
  1268.     err.clear
  1269. End Sub
  1270.  
  1271. '*******************************************************************************'Function EndOfScript
  1272. 'Function to close out the script
  1273. '*******************************************************************************
  1274. Function EndOfScript
  1275.  
  1276.   If blnInstall = true then Call CheckPendingStatus("end")
  1277.   on error goto 0
  1278.   writelog("Windows Update VB Script finished")
  1279.   l.writeline "---------------------------------------------------------------------------"
  1280.   If blnCallRestart = true then writelog("Post-execute action will be called.  " _
  1281.    & " Action is set to: " & restarttext & ".")
  1282.      
  1283.  
  1284.   If blnEmail = 1 Then
  1285.      If searchresult.updates.count = 0 and not blnRebootRequired and StrEmailifAllOK = 0 then
  1286.         writelog ("No updates required, no pending reboot, therefore not sending email")
  1287.      else
  1288.         if strFullDNSName = 1 then
  1289.            strDomainName = wshShell.ExpandEnvironmentStrings("%USERDNSDOMAIN%")
  1290.                  strOutputComputerName = strComputer & "." & StrDomainName
  1291.         else
  1292.            strOutputComputerName = strComputer        
  1293.         end if
  1294.         if emailifallok = 0 or emailifallok = 1 then
  1295.           if instr(strSMTPServer,"x") then
  1296.           else
  1297.            Call SendMail(strFrom,strTo,strSubject & " " & strOutputComputerName,strMessage)
  1298.           end if
  1299.         end if
  1300.      end if
  1301.   Else
  1302.       'l.close
  1303.  
  1304.   End If
  1305.  
  1306.   strMsg = "The script has been configured to " & restarttext _
  1307.         & ".  The update script has detected that this " _
  1308.         & "computer has a reboot pending from a previous update session." & vbcrlf & vbcrlf _
  1309.         & "Would you like to perform this action now?"
  1310.  
  1311.   If silent = 0 and blnPrompt = true Then
  1312.     strResult = MsgBox(strMsg,36,"Perform restart/shutdown action?")
  1313.   ElseIf blnPrompt = false Then
  1314.     strResult = 6
  1315.   End If
  1316.      
  1317.   If blnCallRestart = true Then
  1318.     If strResult = 6 Then call RestartAction
  1319.   Else
  1320.     on error resume next
  1321.     If silent = 0 Then objdiv.innerhtml = strStatus & "<br>This computer has no pending reboots"
  1322.   End If
  1323.  
  1324.   If intSleep > 0 Then
  1325.       ' So the user have a chance to see the last output before closing IE
  1326.      WScript.Sleep intSleep
  1327.       ' Just in case the IE window is already closed by the user
  1328.      On Error Resume Next
  1329.       ' Close the IE window
  1330.      IE.Quit
  1331.       On Error Goto 0
  1332.   End If
  1333.   'l.close
  1334.  wscript.quit
  1335.  
  1336.   Exit Function
  1337.    
  1338. End Function
  1339.  
  1340. '*******************************************************************************
  1341. 'Function CheckPendingStatus
  1342. 'Function to restart the computer if there is a reboot pending...
  1343. '*******************************************************************************
  1344. Function CheckPendingStatus(beforeorafter)
  1345.   Set ComputerStatus = CreateObject("Microsoft.Update.SystemInfo")
  1346.   Select case beforeorafter
  1347.     Case "beginning"
  1348.       strCheck = "Pre-check"
  1349.     Case "end"
  1350.       strCheck = "Post-check"
  1351.     Case Else
  1352.   End Select
  1353.  
  1354.   blnRebootRequired = ComputerStatus.RebootRequired
  1355.  
  1356.   If ComputerStatus.RebootRequired or strForceAction = 1 Then
  1357.      If beforeorafter = "beginning" Then
  1358.         If ComputerStatus.RebootRequired Then strMsg = "This computer has a pending reboot (" & strCheck & ").  Switching to 'detect' mode."
  1359.         If strAction = "prompt" Then blnPrompt = true
  1360.         strAction = "detect"
  1361.         blnCallRestart = true  
  1362.      Else
  1363.         If ComputerStatus.RebootRequired Then strMsg = "This computer has a pending reboot (" & strCheck & ").  Setting PC to perform post-script " _
  1364.           & "execution..."
  1365.         blnCallRestart = true        
  1366.      End If
  1367.   Else
  1368.         If not ComputerStatus.RebootRequired Then strMsg = "This computer does not have any pending reboots (" & strCheck & ")."
  1369.   End If
  1370.  
  1371.      If strMsg <> "" Then writelog(strMsg)
  1372.      If silent = 0 and strMsg <> "" then objdiv.innerhtml = strMsg
  1373.      'wscript.sleep 4000
  1374.          
  1375. End Function
  1376. '*******************************************************************************
Add Comment
Please, Sign In to add comment