maximillianx

Windows-Update.vbs

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