Saturday, August 4, 2012

Installing Windows Updates via Shell Script

I had to dive into the world of shell scripting and do some work there. One of the tasks I had was to automatically install a bunch of Windows Updates on a server. The server could not be connected to the Internet so the updates were provided as separate files. The updates could be a mix of regular executables or Microsoft Update Standalone Packages (.msu). The script gets the name of the folder it runs from and then iterates over the files in this folder. It checks the file extension and runs appropriate command depending on the file being EXE or MSU. It also checks the return value and keeps a counter on the number of updates that reported successful and unsuccessful result, and writes the result of each install into a log file. At the end it displays a message that informs a user about the number of successfully installed and failed updates.

Sub Main

Dim objfso, objShell
Dim iSuccess, iFail
Dim folder, files, sFolder, folderidx, Iretval, return
Set objfso = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("Wscript.Shell")
 
sFolder = left(WScript.ScriptFullName,(Len(WScript.ScriptFullName))-(len(WScript.ScriptName)))
Set folder = objfso.GetFolder(sFolder)
Set logFile = objfso.CreateTextFile("C:\log.txt", TRUE)
Set files = folder.Files
iSuccess = 0
iFail = 0
 
For each folderIdx In files
 If Ucase(Right(folderIdx.name,3)) = "MSU" then
  logFile.WriteLine("Installing " & folderidx.name & "...")
  wscript.echo "Installing " & folderidx.name & "..."
  iretval=objShell.Run ("wusa.exe " & sfolder & folderidx.name & " /quiet /norestart", 1, True)
  If (iRetVal = 0) or (iRetVal = 3010) then
   logFile.WriteLine("Success.")
   wscript.echo "Success."
   iSuccess = iSuccess + 1
  Else
   logFile.WriteLine("Failed.")
   wscript.echo "Failed."
   iFail = iFail + 1
  End If
 ElseIf Ucase(Right(folderIdx.name,3)) = "EXE" Then
  logFile.WriteLine("Installing " & folderidx.name & "...")
  wscript.echo "Installing " & folderidx.name & "..."
  iretval = objShell.Run(folderidx.name & " /q /norestart", 1, True)
  If (iRetVal = 0) or (iRetVal = 3010) then
   logFile.WriteLine("Success.")
   wscript.echo "Success."
   iSuccess = iSuccess + 1
  Else
   logFile.WriteLine("Failed.")
   wscript.echo "Failed."
   iFail = iFail + 1
  End If
 End If
Next

wscript.echo iSuccess & " update(s) installed successfully and " & iFail & " update(s) failed. See C:\log.txt for details."
 
End Sub

Main()
by . Also posted on my website

No comments: