prashant1987

Windows Patch Installation Script on Remote Systems

Posted on: September 4, 2013

I am back here after long time  , and this time again I am up with one more interesting PowerShell script.

Script description :

  This Script will trigger installation of Microsoft WSUS patch updates on remote system. Script has multiple functions , each takes care of different tasks.

  The servers which needs to be patched remotely should be placed in servers.txt . Script will read the servers.txt and uses psexec.exe to initiate the patch installation.

 Update.vbs is a part of the script , and it has to be pushed to the remote computer where scripts triggers the installation of patches. PowerShell utlises this Update.vbs and installs the updates. Once updates are installed , this updates.vbs will be removed from the remote system.

Additionally , Script will prompt for restart option of remote system , ‘Y’ or ‘y’ will trigger the restart on remote machine , also it checks for server online (RDP Status) post reboot.

Below is the script 🙂

Update.Vbs

Set objSession = CreateObject(“Microsoft.Update.Session”)
Set AutoUpdate = CreateObject(“Microsoft.Update.AutoUpdate”)

WScript.Echo “Searching for updates…”

Set UpdateSearcher = objSession.CreateUpdateSearcher
Set SearchResult = UpdateSearcher.Search(” IsAssigned=1 and IsHidden=0 and IsInstalled=0 and Type=’Software'”)

Autoupdate.DetectNow()

If searchResult.Updates.Count = 0 Then
    WScript.Quit(0)
End If

Set updatesToDownload = CreateObject(“Microsoft.Update.UpdateColl”)
For i = 0 To SearchResult.Updates.Count-1
    Set update = SearchResult.Updates.Item(I)
    If Not update.EulaAccepted Then update.AcceptEula
    updatesToDownload.Add(update)
Next

WScript.Echo “Downloading the Updates”

Set downloader = objSession.CreateUpdateDownloader()
downloader.Updates = updatesToDownload
downloader.Download()

Set UpdatesToInstall = CreateObject(“Microsoft.Update.UpdateColl”)
For I = 0 To searchResult.Updates.Count-1
    set update = searchResult.Updates.Item(I)
    If update.IsDownloaded = true Then
        UpdatesToInstall.Add(update)
    End If
Next
WScript.Echo “Installating the Updates…..”
Set installer = objSession.CreateUpdateInstaller()
installer.Updates = updatesToInstall
installer.Install()

WScript.Quit(0)

PowerShell Script

# Name : Install-Patches on remote system
#Author : Prashant Girennavar.
#DateCreated : 4th Sept 2013.

# Function to create a Temp folder on remote machine if it does not exist
Function TempFolderCheck($Server)
{
 If(!(Test-Path \\$Server\c$\temp))
 {
   New-Item -type directory -path \\$Server\c$\Temp
 }
}

#Function to copy Update.vbs script on remote machine
Function BatchVBCopy($Server)
{
Write-host “VB Script is being copied on $Server”
Copy-Item -Path \\$SourceServer\C$\update.vbs -destination \\$Server\c$\Temp
}

#Function to trigger the patch installation on remote machine
Function InstallPatch($Server)
{
 try
 {
 .\psexec.exe -accepteula -s -i \\$Server cscript.exe C:\temp\update.vbs
 if($LASTEXITCODE -eq 0) #Check if PSEXEC executed successfully
 {
 Write-Host “$Server” Patched Successfully
 Remove-Item \\$Server\C$\Temp\Update.vbs #Remove the update.vbs from remote system
 $Reboot =  Read-Host “Do you wish to Reboot the system now? say Y to reboot / N to decline”
 if(($Reboot -eq “Y”)-or($Reboot -eq “y”))
 {
  Write-Host “Now Rebooting the $Server , Please wait ….”
  Restart-Computer -ComputerName $Server -Force #Restarting remote computer post patch installation
 }
}
 Else
 {
 Write-Host “$Server” Unable to patch the server please check
 }
 }
 Catch
 {
Write-Host “$Server” Encountered an exception
 }
 }

$Servers = Get-Content C:\Servers.txt # Get the server list which needs to be patched
Foreach($Server in $Servers)
{
TempFolderCheck($Server) #Call TempFolderCheck Function
BatchVBCopy($Server) #Call BatchVBCopy Function
InstallPatch($Server) #Call InstallPatch Function
}

Start-Sleep -Seconds 300 #Sleep for 5 mins

#Checking for server online status
Write-Host “Now Checking if all the servers are online post patch installation”
$Servers = Get-Content C:\Servers.txt
Foreach($Server in $Servers)
{
 $Connection = New-Object Net.Sockets.TcpClient # Add RDP Port .NET class
 $Connection.Connect($Server,’3389′) #Check for RDP Port 3389 status
 if ($Connection.Connected) #Check connection has been established
 {
  Write-Host “$Server is online after patching” -ForegroundColor Green
 }
 else
 {
 Write-Host ” $Server seems to have some problem , Please check it manually” -ForegroundColor Red
 }
}

$SourceServer = > where Update.VBS is stored

I Hope this script will help

Thanks,

_Prashant_

Advertisements

4 Responses to "Windows Patch Installation Script on Remote Systems"

Hi,

We have two DC in our environment (Primary and Secondary DC). Last success replication was in 2013-06-07 23:06:12.
This issue causing a lot of problems in our environment as instance I tried to join a server to the domain but it failed and gives me the following message error:

The following error occurred attempting to join the domain “domain name”:
Logon Failure: The target account name is incorrect

Below is the result of repadmin /showrepl command that I ran inside DC:

Please advice
KC

C:\Users\admin>repadmin /showrepl
Repadmin: running command /showrepl against full DC localhost
Default-First-Site-Name\ADCSRV01
DSA Options: IS_GC DISABLE_INBOUND_REPL DISABLE_OUTBOUND_REPL
Site Options: (none)
DSA object GUID: 98873683-99f6-49f2-a2c2-c26b73bb375f
DSA invocationID: 289baa7f-8621-4a87-8af1-63394b42a93d
==== INBOUND NEIGHBORS ======================================
DC=securedlogin,DC=local
Default-First-Site-Name\DPMSRV01 via RPC
DSA object GUID: db2ad97e-aa25-4c8a-974a-d3e69765df04
Last attempt @ 2013-08-21 21:45:31 failed, result 8457 (0x2109):
The destination server is currently rejecting replication requests.
33818 consecutive failure(s).
Last success @ 2013-06-07 23:06:12.
CN=Configuration,DC=securedlogin,DC=local
Default-First-Site-Name\DPMSRV01 via RPC
DSA object GUID: db2ad97e-aa25-4c8a-974a-d3e69765df04
Last attempt @ 2013-08-21 21:45:31 failed, result 8457 (0x2109):
The destination server is currently rejecting replication requests.
1793 consecutive failure(s).
Last success @ 2013-06-07 22:45:30.
CN=Schema,CN=Configuration,DC=securedlogin,DC=local
Default-First-Site-Name\DPMSRV01 via RPC
DSA object GUID: db2ad97e-aa25-4c8a-974a-d3e69765df04
Last attempt @ 2013-08-21 21:45:31 failed, result 8457 (0x2109):
The destination server is currently rejecting replication requests.
1791 consecutive failure(s).
Last success @ 2013-06-07 22:45:30.
DC=ForestDnsZones,DC=securedlogin,DC=local
Default-First-Site-Name\DPMSRV01 via RPC
DSA object GUID: db2ad97e-aa25-4c8a-974a-d3e69765df04
Last attempt @ 2013-08-21 21:45:31 failed, result 8457 (0x2109):
The destination server is currently rejecting replication requests.
1791 consecutive failure(s).
Last success @ 2013-06-07 22:45:30.
DC=DomainDnsZones,DC=securedlogin,DC=local
Default-First-Site-Name\DPMSRV01 via RPC
DSA object GUID: db2ad97e-aa25-4c8a-974a-d3e69765df04
Last attempt @ 2013-08-21 21:45:31 failed, result 8457 (0x2109):
The destination server is currently rejecting replication requests.
1873 consecutive failure(s).
Last success @ 2013-06-07 22:45:30.
DsReplicaGetInfo() failed with status 8453 (0x2105):
Replication access was denied.
DsReplicaGetInfo() failed with status 8453 (0x2105):
Replication access was denied.

There is a MS KB article on this .

http://support.microsoft.com/kb/2023007

Did you had a chance to have a look at it?

-Prashant Girennavar.

Hi Prashant … this very good script.. I am facing some issue in following script it will not showing the exact result.

List of servers- C:\script\input.txt
List of patches- C:\script\kb.txt
output file – C:\script\Pat_Install_Status_KB.htm

Dim objFSO, objTextFile, RootDir, FileOutput, strComputer, objWMIService, Count

Const ForReading = 1

Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objTextFile = objFSO.OpenTextFile(“C:\script\input.txt”, ForReading)
Set objkbFile = objFSO.OpenTextFile(“C:\script\kb.txt”, ForReading)

Dim strHotFix
set FileOutput = objFSO.CreateTextFile(“C:\script\Pat_Install_Status_KB.htm”,true,false)

fileOutput.WriteLine(“Installed Patches Information”)
fileOutput.WriteLine(“”)
fileOutput.WriteLine(“”)
fileOutput.WriteLine(“Computer NameDescriptionHotfix IDInstall StatusInstalled OnInstalled By”)

Do Until objTextFile.AtEndOfStream
strComputer = objTextFile.Readline
Count = 0
‘Query command
Set objWMIService = GetObject(“winmgmts:” & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”)

Dim QFEs
Set QFEs = objWMIService.ExecQuery (“Select * from win32_QuickFixEngineering”)

Dim strOutput
Dim QFE
For Each QFE in QFEs

Do Until objkbFile.AtEndOfStream
strHotFix = objkbFile.Readline
if QFE.HotFixID = strHotFix then
strOutput = “”
strOutput = strOutput + “” & strComputer & “” &_
“” & QFE.Description & “” &_
“” & QFE.HotFixID & “” &_
“” & “Installed” & “” &_
“” & QFE.InstalledOn & “” &_
“” & QFE.InstalledBy & “”
Count= Count + 1
fileOutput.WriteLine(strOutPut)
fileOutput.WriteLine(“”)
end if

‘ strOutPut=””
loop
Next
if Count = 0 then
strOutput = “”
strOutput = strOutput + “” & strComputer & “” &_
“” & “-” & “” &_
“” & strHotfix & “” &_
“” & “Not Installed” & “” &_
“” & “-” & “” &_
“” & “-” & “”
fileOutput.WriteLine(strOutPut)
fileOutput.WriteLine(“”)
end if
Loop

fileOutput.WriteLine(“”)
wscript.echo “Result saved in Pat_Install_Status_KB.html file at specified location in line no 15 of this script”
WScript.Quit

VB Script is being copied on XXXXX

PsExec v2.11 – Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals – http://www.sysinternals.com

cscript.exe exited on XXXXX with error code 1.
XXXXXXX Unable to patch the server please check

Getting Above Error while run the Command

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: