Pages

Monday, February 25, 2019

Attempting to use VMware vSphere PowerCLI's Connect-VIServer to a vCenter instance fails with: "The underlying connection was closed: An unexpected error occurred on a send."

Problem

You have VMware vSphere PowerCLI version 5.1.0.4977 installed:

You attempt to connect to a vSphere vCenter 6.7:

… using the Connect-VIServer cmdlet but it immediately fails with:

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI> Connect-VIServer vCenter.contoso.local

Connect-VIServer : 2/22/2019 11:41:37 AM Connect-VIServer The underlying connection was closed: An unexpected error

occurred on a send.

At line:1 char:1

+ Connect-VIServer vCenter.contoso.local

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : NotSpecified: (:) [Connect-VIServer], ViError

+ FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_WebException,VMware.VimAutomation.ViCore.Cmdl

ets.Commands.ConnectVIServer

PowerCLI C:\Program Files (x86)\VMware\Infrastructure\vSphere PowerCLI>

Solution

The reason why this error is thrown is because vCenter 6.7 only has TLS 1.2 enabled while TLS 1.0 and 1.1 is disabled by default so the older PowerCLI version installed, which attempts to connect via a one of the lower TLS versions will fail. The proper method of resolving this issue is to upgrade the old PowerCLI version to the latest one with the cmdlet Install-Module -Name VMware.PowerCLI as shown in the following PowerShell Gallery:

https://www.powershellgallery.com/packages/VMware.PowerCLI/11.1.0.11289667

The alternate solution is to force the .NET to use the appropriate TLS version for connecting to the vCenter:

Enabling the TLSv1.1 and TLSv1.2 protocols for PowerCLI (2137109)
https://kb.vmware.com/s/article/2137109

· For 32-bit processes, change the following registry key value to 1.

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\[.NET_version]
Value: SchUseStrongCrypto (DWORD)

· For 64-bit processes, in addition to the above registry key, change the following registry key value to 1.

Key: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\[.NET_version]
Value: SchUseStrongCrypto (DWORD)

This workaround was handy for the project where the environment did not allow me to download or install any binaries on the endpoint I was using but I did find that the workaround with vSphere PowerCLI 5.1.0.4977 would only work with the 32-Bit version:

Adding the two registry keys in did not allow the 64-Bit version to connect.

Additional information - Invalid server certificate

Note that if you attempt to use the IP address of the vCenter to connect then you will receive the following error indicating that the certificate being presented is invalid:

PS C:\users\tluk\Downloads\vCheck-vSphere-master\vCheck-vSphere-master> Connect-VIServer 10.10.10.24

Connect-VIServer : 2/22/2019 3:47:15 PM Connect-VIServer Error: Invalid server certificate. Use

Set-PowerCLIConfiguration to set the value for the InvalidCertificateAction option to Prompt if you'd like to connect

once or to add a permanent exception for this server.

Additional Information: Could not establish trust relationship for the SSL/TLS secure channel with authority

'10.10.10.24'.

At line:1 char:1

+ Connect-VIServer 10.10.10.24

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

+ CategoryInfo : SecurityError: (:) [Connect-VIServer], ViSecurityNegotiationException

+ FullyQualifiedErrorId : Client20_ConnectivityServiceImpl_Reconnect_CertificateError,VMware.VimAutomation.ViCore.

Cmdlets.Commands.ConnectVIServer

It is best practice to have a trusted certificate installed and to connect with the FQDN of the vCenter but if you do not meet either of the criteria then you can configure PowerCLI to ignore the certificate error with the following cmdlet:

Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false

Scope ProxyPolicy DefaultVIServerMode InvalidCertificateAction DisplayDeprecationWarnings WebOperationTimeout

Seconds

----- ----------- ------------------- ------------------------ -------------------------- -------------------

Session UseSystemProxy Multiple Ignore True 300

User Ignore

AllUsers

Alternatively, if you want to install the self-signed certificate on the device that you are initiating the connection from so you can connect via the FQDN, you can use the same instructions I provided in the solution of one of my previous blog posts to download and install the certificate into the trusted store:

Attempting to upload a file onto a datastore with vSphere Client 6.5 fails with: "The operation failed."
http://terenceluk.blogspot.com/2018/11/attempting-to-upload-file-onto.html

Monday, February 18, 2019

Mapping drives and printers for Citrix XenApp / XenDesktop published applications with batch and VBS scripts based on AD group membership

One of the more frequent questions I’ve been asked for Citrix XenApp / XenDesktop published applications is whether there is a way to map network drives and printers based on AD group membership for applications that are published via a batch file. There are several ways to do this but if you want to specifically control the mappings from within a VBS script then below is an example of how to do this.

The first step in the process is to create two files:

  1. A batch file that the published application within Citrix XenApp / XenDesktop will execute to launch the application
  2. A VBS script that will map the respective network drives and printers based on group membership

For this example, the batch file will be named MapLaunch.bat and the vbs script that will control the network drives and printers mapping will be MapDrivesPrinters.vbs as shown below:

The contents of the batch file MapLaunch.bat will be simple as it simply calls the VBS script to map the network drives and printers, followed by starting the Citrix application defined in the Command line argument (option): field in the Application Settings:

cscript C:\Scripts\MapDrivesPrinters.vbs

start "Citrix" %*

timeout /T 1 /nobreak

The next step is to create a vbs script that would map the network drives and printers based on AD membership. There are plenty of scripts available and one of the scripts I’ve used in the past is by Richard L. Mueller and can be found here: https://www.rlmueller.net/Logon6.htm

The script is fairly straight forward to use but I’ll paste a sample one below with the customizations highlighted in red.

' Logon6.vbs
' VBScript logon script program.
'
' ----------------------------------------------------------------------
' Copyright (c) 2004-2010 Richard L. Mueller
' Hilltop Lab web site - http://www.rlmueller.net
' Version 1.0 - March 28, 2004
' Version 1.1 - July 30, 2007 - Escape any "/" characters in DN's.
' Version 1.2 - November 6, 2010 - No need to set objects to Nothing.
'
' You have a royalty-free right to use, modify, reproduce, and
' distribute this script file in any way you find useful, provided that
' you agree that the copyright owner above has no warranty, obligations,
' or liability for such use.

Option Explicit

Dim objRootDSE, objTrans, strNetBIOSDomain, objNetwork, strNTName
Dim strUserDN, strComputerDN, objGroupList, objUser, strDNSDomain
Dim strComputer, objComputer
Dim strHomeDrive, strHomeShare
Dim adoCommand, adoConnection, strBase, strAttributes

' Constants for the NameTranslate object.
Const ADS_NAME_INITTYPE_GC = 3
Const ADS_NAME_TYPE_NT4 = 3
Const ADS_NAME_TYPE_1779 = 1

Set objNetwork = CreateObject("Wscript.Network")

' Loop required for Win9x clients during logon.
strNTName = ""
On Error Resume Next
Do While strNTName = ""
     strNTName = objNetwork.UserName
     Err.Clear
     If (Wscript.Version > 5) Then
         Wscript.Sleep 100
     End If
Loop
On Error GoTo 0

' Determine DNS domain name from RootDSE object.
Set objRootDSE = GetObject("LDAP://RootDSE")
strDNSDomain = objRootDSE.Get("defaultNamingContext")

' Use the NameTranslate object to find the NetBIOS domain name from the
' DNS domain name.
Set objTrans = CreateObject("NameTranslate")
objTrans.Init ADS_NAME_INITTYPE_GC, ""
objTrans.Set ADS_NAME_TYPE_1779, strDNSDomain
strNetBIOSDomain = objTrans.Get(ADS_NAME_TYPE_NT4)
' Remove trailing backslash.
strNetBIOSDomain = Left(strNetBIOSDomain, Len(strNetBIOSDomain) - 1)

' Use the NameTranslate object to convert the NT user name to the
' Distinguished Name required for the LDAP provider.
objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain & "\" & strNTName
strUserDN = objTrans.Get(ADS_NAME_TYPE_1779)
' Escape any forward slash characters, "/", with the backslash
' escape character. All other characters that should be escaped are.
strUserDN = Replace(strUserDN, "/", "\/")

' Bind to the user object in Active Directory with the LDAP provider.
Set objUser = GetObject("LDAP://" & strUserDN)

' Map a network drive if the user is a member of the group.
If (IsMember(objUser, "Contoso_Services") = True) Then
     On Error Resume Next
     objNetwork.MapNetworkDrive "G:", "\\fileserver\conto"
     If (Err.Number <> 0) Then
         On Error GoTo 0
         objNetwork.RemoveNetworkDrive "G:", True, True
         objNetwork.MapNetworkDrive "G:", "\\fileserver\conto"
     End If
     On Error GoTo 0
End If

' Map a network drive if the user is a member of the group.
If (IsMember(objUser, "HPC_Users") = True) Then
     On Error Resume Next
     objNetwork.MapNetworkDrive "R:", "\\HPCServer\HPC_WorkArea$"
     If (Err.Number <> 0) Then
         On Error GoTo 0
         objNetwork.RemoveNetworkDrive "R:", True, True
         objNetwork.MapNetworkDrive "R:", "\\HPCServer\HPC_WorkArea$"
     End If
     On Error GoTo 0
End If

' Map a network drive if the user is a member of the group.
If (IsMember(objUser, "Domain Users") = True) Then
     On Error Resume Next
     objNetwork.MapNetworkDrive "S:", "\\fileserver\s_root$"
     If (Err.Number <> 0) Then
         On Error GoTo 0
         objNetwork.RemoveNetworkDrive "S:", True, True
         objNetwork.MapNetworkDrive "S:", "\\fileserver\s_root$"
     End If
     On Error GoTo 0
End If

' Map a network drive if the user is a member of the group.
If (IsMember(objUser, "SecureClaims") = True) Then
     On Error Resume Next
     objNetwork.MapNetworkDrive "T:", "\\fileserver\SecureClaimsArea$"
     If (Err.Number <> 0) Then
         On Error GoTo 0
         objNetwork.RemoveNetworkDrive "T:", True, True
         objNetwork.MapNetworkDrive "T:", "\\fileserver\SecureClaimsArea$"
     End If
     On Error GoTo 0
End If

' Map a network drive if the user is a member of the group.
If (IsMember(objUser, "ReInsur_Services") = True) Then
     On Error Resume Next
     objNetwork.MapNetworkDrive "X:", "\\fileserver\ReLife"
     If (Err.Number <> 0) Then
         On Error GoTo 0
         objNetwork.RemoveNetworkDrive "X:", True, True
         objNetwork.MapNetworkDrive "X:", "\\fileserver\ReLife"
     End If

     On Error GoTo 0
End If

' Use the NameTranslate object to convert the NT name of the computer to
' the Distinguished name required for the LDAP provider. Computer names
' must end with "$".
strComputer = objNetwork.computerName
objTrans.Set ADS_NAME_TYPE_NT4, strNetBIOSDomain _
     & "\" & strComputer & "$"
strComputerDN = objTrans.Get(ADS_NAME_TYPE_1779)
' Escape any forward slash characters, "/", with the backslash
' escape character. All other characters that should be escaped are.
strComputerDN = Replace(strComputerDN, "/", "\/")

' Add a printer connection if the user is a member of the group.
If (IsMember(objUser, "Domain Users") = True) Then
     Set objNetwork = CreateObject("WScript.Network")
     objNetwork.AddWindowsPrinterConnection "\\PrintServer\Xerox7855B PCL6"
     objNetwork.AddWindowsPrinterConnection "\\PrintServer\Xerox7855A PCL6"
     objNetwork.AddWindowsPrinterConnection "\\PrintServer\Lexmark Universal v2 PS3"
     objNetwork.SetDefaultPrinter "\\PrintServer\Xerox7855A PCL6"
End If

' Clean up.
If (IsObject(adoConnection) = True) Then
     adoConnection.Close
End If

Function IsMember(ByVal objADObject, ByVal strGroupNTName)
     ' Function to test for group membership.
     ' objADObject is a user or computer object.
     ' strGroupNTName is the NT name (sAMAccountName) of the group to test.
     ' objGroupList is a dictionary object, with global scope.
     ' Returns True if the user or computer is a member of the group.
     ' Subroutine LoadGroups is called once for each different objADObject.

    ' The first time IsMember is called, setup the dictionary object
     ' and objects required for ADO.
     If (IsEmpty(objGroupList) = True) Then
         Set objGroupList = CreateObject("Scripting.Dictionary")
         objGroupList.CompareMode = vbTextCompare

        Set adoCommand = CreateObject("ADODB.Command")
         Set adoConnection = CreateObject("ADODB.Connection")
         adoConnection.Provider = "ADsDSOObject"
         adoConnection.Open "Active Directory Provider"
         adoCommand.ActiveConnection = adoConnection

        Set objRootDSE = GetObject("LDAP://RootDSE")
         strDNSDomain = objRootDSE.Get("defaultNamingContext")

        adoCommand.Properties("Page Size") = 100
         adoCommand.Properties("Timeout") = 30
         adoCommand.Properties("Cache Results") = False

        ' Search entire domain.
         strBase = "<LDAP://" & strDNSDomain & ">"
         ' Retrieve NT name of each group.
         strAttributes = "sAMAccountName"

        ' Load group memberships for this user or computer into dictionary
         ' object.
         Call LoadGroups(objADObject)
     End If
     If (objGroupList.Exists(objADObject.sAMAccountName & "\") = False) Then
         ' Dictionary object established, but group memberships for this
         ' user or computer must be added.
         Call LoadGroups(objADObject)
     End If
     ' Return True if this user or computer is a member of the group.
     IsMember = objGroupList.Exists(objADObject.sAMAccountName & "\" _
         & strGroupNTName)
End Function

Sub LoadGroups(ByVal objADObject)
     ' Subroutine to populate dictionary object with group memberships.
     ' objGroupList is a dictionary object, with global scope. It keeps track
     ' of group memberships for each user or computer separately. ADO is used
     ' to retrieve the name of the group corresponding to each objectSid in
     ' the tokenGroup array. Based on an idea by Joe Kaplan.

    Dim arrbytGroups, k, strFilter, adoRecordset, strGroupName, strQuery

    ' Add user name to dictionary object, so LoadGroups need only be
     ' called once for each user or computer.
     objGroupList.Add objADObject.sAMAccountName & "\", True

    ' Retrieve tokenGroups array, a calculated attribute.
     objADObject.GetInfoEx Array("tokenGroups"), 0
     arrbytGroups = objADObject.Get("tokenGroups")

    ' Create a filter to search for groups with objectSid equal to each
     ' value in tokenGroups array.
     strFilter = "(|"
     If (TypeName(arrbytGroups) = "Byte()") Then
         ' tokenGroups has one entry.
         strFilter = strFilter & "(objectSid=" _
             & OctetToHexStr(arrbytGroups) & ")"
     ElseIf (UBound(arrbytGroups) > -1) Then
         ' TokenGroups is an array of two or more objectSid's.
         For k = 0 To UBound(arrbytGroups)
             strFilter = strFilter & "(objectSid=" _
                 & OctetToHexStr(arrbytGroups(k)) & ")"
         Next
     Else
         ' tokenGroups has no objectSid's.
         Exit Sub
     End If
     strFilter = strFilter & ")"

    ' Use ADO to search for groups whose objectSid matches any of the
     ' tokenGroups values for this user or computer.
     strQuery = strBase & ";" & strFilter & ";" _
         & strAttributes & ";subtree"
     adoCommand.CommandText = strQuery
     Set adoRecordset = adoCommand.Execute

    ' Enumerate groups and add NT name to dictionary object.
     Do Until adoRecordset.EOF
         strGroupName = adoRecordset.Fields("sAMAccountName").Value
         objGroupList.Add objADObject.sAMAccountName & "\" _
             & strGroupName, True
         adoRecordset.MoveNext
     Loop
     adoRecordset.Close

End Sub

Function OctetToHexStr(ByVal arrbytOctet)
     ' Function to convert OctetString (byte array) to Hex string,
     ' with bytes delimited by \ for an ADO filter.

    Dim k
     OctetToHexStr = ""
     For k = 1 To Lenb(arrbytOctet)
         OctetToHexStr = OctetToHexStr & "\" _
             & Right("0" & Hex(Ascb(Midb(arrbytOctet, k, 1))), 2)
     Next
End Function

Monday, February 11, 2019

Using InstallSoftwareRemotely.ps1 to upgrade VMware Horizon View Agent

I’ve had a lot of colleagues in the past ask me what I would use for smaller clients who did not have a software deployment tool such as SCCM to install or upgrade applications and the solution I typically present is the InstallSoftwareRemotely.ps1 PowerScript found here:

Install software on multiple computers remotely with PowerShell
https://gallery.technet.microsoft.com/scriptcenter/Install-software-on-9278d883

I’ve always used this script to perform small deployments and this blog post serves as a demonstration of how to use it.

Prerequisites for InstallSoftwareRemotely.ps1

The items that you’ll need to prepare as prerequisites before executing the command are as follows:

  1. An administrator account on the target computers that you’ll be installing applications on (a domain admin would suffice)
  2. Download Psexec.exe from https://docs.microsoft.com/en-us/sysinternals/downloads/psexec and place the executable C:\Windows\System32 so the PS script could execute the command to enable PSRemoting
  3. Place the software installation file, in this case the VMware Horizon View agent, into a network share accessible by the target computer and the account you will be running the PS script and ensure that it is not blocked (see one of my previous blog posts for more information about why this is important http://terenceluk.blogspot.com/2018/05/attempting-to-use-invoke-command.html)
  4. Arguments (if reqiured) for the installation executable
  5. A CSV file containing the computers that the software will be installed on (see the TechNet article’s description of the ComputerList for more information about the accepted sources)
  6. Amount numeric value for the number of retries for the installation
  7. The application name to check and see if it exists before installing the application (more information provided below)
  8. The application version to check and see if it exists before installing the application (more information provided below)
  9. Determine whether the target computer is 32-bit or 64-bit

There are several other switches available for the InstallSoftwareRemotely.ps1 but the ones mentioned above or the ones I typically use.  Please refer to the TechNet article for more information about the other ones available.

-----------------------------------------------------------------------------------------------------------------------------

Determining the application name and application version to check before installing

One of the things you can do with the InstallSoftwareRemotely.ps1 PS script is to have it check to see if the software you’re attempting to install already exists on the target computer.  The information required can be found via the following registry path:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{IdentifyingNumber}

DisplayName

DisplayVersion

Here is an example of where the VMware Horizon View Agent 6.2.1.3284564 can be found:

Note that you can also use PowerShell to required information as described here:

Use PowerShell to Find and Uninstall Software
https://blogs.technet.microsoft.com/heyscriptingguy/2011/12/14/use-powershell-to-find-and-uninstall-software/

----------------------------------------------------------------------------------------------------------------------------

Using a CSV for the target computers

Below is a screenshot of the format for a CSV file if you choose to use it as a list of the target computers:

Modification to the PS Script (for VMware Horizon View Agent only)

The slight modification I made to the PS script includes a restart command that executes when the installation of the application is completed.  The reason why chose to suppress the reboot with the switch that the VMware Horizon View Agent accepts is because allow the agent installer to restart the target computer would interrupt the InstallSoftwareRemotely.ps1 script before it completes thus causing errors to be thrown.  This should be applied to any applications that automatically restart upon completing its install.

Simply insert the Restart-Computer -ComputerName $Computer as shown in the screenshot below to achieve this:

The PowerShell script and required parameters

The following is the final PS script and its required parameters for the VMware Horizon View Agent install:

.\InstallSoftwareRemotely.ps1 -AppPath '\\fp09\tech\Software\VMware\VMware Horizon View\VMware Horizon View 6.2.1\Agent\VMware-viewagent-x86_64-6.2.1-3284564.exe' -AppArgs '/S /V"/qn REBOOT=Reallysuppress' -CSV 'C:\Scripts\VDIs.csv' -Retries 2 -AppName 'VMware Horizon View Agent' -AppVersion '6.2.1.3284564' -WMIQuery 'select * from Win32_Processor where DeviceID="CPU0" and AddressWidth="64"' -EnablePSRemoting -Credential

Note that the:

WMIQuery 'select * from Win32_Processor where DeviceID="CPU0" and AddressWidth="64"'

… is to determine whether the target computer is a 32-bit or 64-bit Windows OS.  This is necessary because the agent we’re installing is for a 64-bit OS.

The resulting output of the script should look similar to the screenshot below:

Note that I am unable to determine what causes the error code 1641 during the VMware Horizon View Agent install even though it is a successful as this does not happen to other applications I’ve used this PS script with so be aware of the following:

  • 1641 is success
  • 1603 is failure

-----------------------------------------------------------------------------------------------------------------------------

InstallSoftwareRemotely.ps1 Script with modification

Below is a copy and paste of the actual script I used for this demonstration.  Be advised that the script would likely receive updates and changes in the future.

<#

.SYNOPSIS

Install software remotely in a group of computers and retry the installation in case of error.

.DESCRIPTION

This script install software remotely in a group of computers and retry the installation in case of error.

It uses PowerShell to perform the installation. Target computer must allow Windows PowerShell Remoting.

Script can try to enable Windows PowerShell Remoting using Microsoft Sysinternals Psexec with the paramenter -EnablePSRemoting.

If PSExec is not found on computer, script asks to the user for download it and extract in system folder.

.PARAMETER AppPath

Path to the application executable, It can be a network or local path because entire folder will be copied to remote computer before installing and deleted after installation.

Example: 'C:\Software\TeamViewer\TeamvieverHost.msi' (Folder TeamViewer will be copied to remote computer before run ejecutable)

.PARAMETER AppArgs

Application arguments to perform silent installation.

Example: '/S /R settings.reg'

.PARAMETER LocalPath

Local path of the remote computer where copy application directory.

Default: 'C:\temp'

.PARAMETER Retries

Number of times to retry failed installations.

Default: 5

.PARAMETER TimeBetweenRetries

Seconds to wait before retrying failed installations.

Default: 60

.PARAMETER ComputerList

List of computers in install software. You can only use one source of target computers: ComputerList, OU or CSV.

Example: Computer001,Computer002,Computer003 (Without quotation marks)

.PARAMETER OU

OU containing computers in which install software.

RSAT for AD module for PowerShell must be installed in order to query AD.

If you run script from a Domain Controller, AD module for PowerShell is already enabled.

You can only use one source of target computers: ComputerList, OU or CSV.

Example: 'OU=Test,OU=Computers,DC=CONTOSO,DC=COM'

.PARAMETER CSV

CSV file containing computers in which install software. You can only use one source of target computers: ComputerList, OU or CSV.

Example: 'C:\Scripts\Computers.csv'

CSV Format:

Name

Computer001

Computer002

Computer003

.PARAMETER LogPath

Path where save log file.

Default: My Documents

.PARAMETER Credential

Script will ask for an account to perform remote installation.

.PARAMETER EnablePSRemoting

Try to enable PSRemoting on failed computers using Psexec. Psexec has to be on system path.

If PSExec is not found. Script ask to download automatically PSTools and copy them to C:\Windows\System32.

.PARAMETER AppName

App name as shown in registry to check if app is installed on remote computer and not reinstall it.

You can check app name on a computer with it installed looking at:

'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\'

'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\'

Example: 'TightVNC'

Default: None

.PARAMETER AppVersion

App name as shown in registry to check if app is installed on remote computer and not reinstall it.

If not specified and AppName has a value, version will be ignored.

You can check app version on a computer with it installed looking at:

'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\'

'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\'

Example: '2.0.8.1'

Default: all

.PARAMETER WMIQuery

WMI Query to execute in remote computers. Software will be installed if query returns values.

Example: 'select * from Win32_Processor where DeviceID="CPU0" and AddressWidth="64"' (64 bit computers)

Example: 'select * from Win32_Processor where DeviceID="CPU0" and AddressWidth="32"' (32 bit computers)

Default: None

.EXAMPLE

TightVNC -> .\InstallSoftwareRemotely.ps1 -AppPath 'C:\Scripts\TightVNC\tightvnc-2.8.8-gpl-setup-64bit.msi' -AppArgs '/quiet /norestart ADDLOCAL="Server" SERVER_REGISTER_AS_SERVICE=1 SERVER_ADD_FIREWALL_EXCEPTION=1 SERVER_ALLOW_SAS=1 SET_USEVNCAUTHENTICATION=1 VALUE_OF_USEVNCAUTHENTICATION=1 SET_PASSWORD=1 VALUE_OF_PASSWORD=Password.01 SET_USECONTROLAUTHENTICATION=1 VALUE_OF_USECONTROLAUTHENTICATION=1 SET_CONTROLPASSWORD=1 VALUE_OF_CONTROLPASSWORD=3digits.01' -OU 'OU=Central,OU=Computers,DC=Contoso,DC=local' -Retries 2 -AppName 'TightVNC' -AppVersion '2.8.8.0' -EnablePSRemoting -WMIQuery 'select * from Win32_Processor where DeviceID="CPU0" and AddressWidth="64"'

.EXAMPLE

TightVNC Mirage Driver -> .\InstallSoftwareRemotely.ps1 -AppPath 'C:\Scripts\TightVNC\dfmirage-setup-2.0.301.exe' -AppArgs '/verysilent /norestart' -OU 'OU=Central,OU=Computers,OU=MyBusiness,DC=Contoso,DC=local' -Retries 2 -AppName 'DemoForge Mirage Driver for TightVNC 2.0' -AppVersion '2.0' -EnablePSRemoting -WMIQuery 'select * from Win32_Processor where DeviceID="CPU0" and AddressWidth="64"'

.EXAMPLE

InstallSoftwareRemotely.ps1 -AppPath "C:\Temp\Software\Miranda\miranda-im-v0.10.75-unicode.exe" -AppArgs "/S" -ComputerList Computer001,Computer002,Computer003 -AppName "Miranda IM 0.10.75" -AppVersion "0.10.75"

.EXAMPLE

InstallSoftwareRemotely.ps1 -AppPath "C:\Temp\Software\Miranda\miranda-im-v0.10.75-unicode.exe" -AppArgs "/S" -CSV "C:\Computers.csv" -Credential -EnablePSRemoting

.EXAMPLE

InstallSoftwareRemotely.ps1 -AppPath "\\Server01\Software\Miranda\miranda-im-v0.10.75-unicode.exe" -AppArgs "/S" -OU "OU=Test,OU=Computers,DC=CONTOSO,DC=COM"

.NOTES

Author: Juan Granados

Date: November 2017

#>

Param(

[Parameter(Mandatory=$true,Position=0)]

[ValidateNotNullOrEmpty()]

[string]$AppPath,

[Parameter(Mandatory=$false,Position=1)]

[ValidateNotNullOrEmpty()]

[string]$AppArgs="None",

[Parameter(Mandatory=$false,Position=2)]

[ValidateNotNullOrEmpty()]

[string]$LocalPath="C:\temp",

[Parameter(Mandatory=$false,Position=3)]

[ValidateNotNullOrEmpty()]

[int]$Retries=5,

[Parameter(Mandatory=$false,Position=4)]

[ValidateNotNullOrEmpty()]

[int]$TimeBetweenRetries=60,

[Parameter(Mandatory=$false,Position=5)]

[ValidateNotNullOrEmpty()]

[string[]]$ComputerList,

[Parameter(Mandatory=$false,Position=6)]

[ValidateNotNullOrEmpty()]

[string]$OU,

[Parameter(Mandatory=$false,Position=7)]

[ValidateNotNullOrEmpty()]

[string]$CSV,

[Parameter(Mandatory=$false,Position=7)]

[ValidateNotNullOrEmpty()]

[string]$LogPath=[Environment]::GetFolderPath("MyDocuments"),

[Parameter(Position=9)]

[switch]$EnablePSRemoting,

[Parameter(Position=10)]

[switch]$Credential,

[Parameter(Mandatory=$false,Position=11)]

[ValidateNotNullOrEmpty()]

[string]$AppName="None",

[Parameter(Mandatory=$false,Position=12)]

[ValidateNotNullOrEmpty()]

[string]$AppVersion="all",

[Parameter(Mandatory=$false,Position=13)]

[ValidateNotNullOrEmpty()]

[string]$WMIQuery="None"

)

#Functions

Add-Type -AssemblyName System.IO.Compression.FileSystem

function Unzip

{

param([string]$zipfile, [string]$outpath)

[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)

}

Function Copy-WithProgress

{

Param([string]$Source,[string]$Destination)

$Source=$Source.tolower()

$Filelist=Get-Childitem $Source –Recurse

$Total=$Filelist.count

$Position=0

If(!(Test-Path $Destination)){

New-Item $Destination -Type Directory | Out-Null

}

foreach ($File in $Filelist){

$Filename=$File.Fullname.tolower().replace($Source,'')

$DestinationFile=($Destination+$Filename)

try{

Copy-Item $File.FullName -Destination $DestinationFile -Force

}catch{throw $_.Exception}

$Position++

Write-Progress -Activity "Copying data from $source to $Destination" -Status "Copying File $Filename" -PercentComplete (($Position/$Total)*100)

}

}

Function Set-Message([string]$Text,[string]$ForegroundColor="White",[int]$Append=$True){

if ($Append){

$Text | Out-File $LogPath -Append

}

else {

$Text | Out-File $LogPath

}

Write-Host $Text -ForegroundColor $ForegroundColor

}

function Get-InstalledApps

{

if ([IntPtr]::Size -eq 4) {

$regpath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'

}

else {

$regpath = @(

'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'

'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'

)

}

Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} |

Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |

Sort DisplayName

#$result = Get-InstalledApps | where {$_.DisplayName -like $appToMatch}

}

Function CheckSoftwareInstalled([string]$Computer){

If ($Cred){

try{

Return Invoke-Command -computername $Computer -ScriptBlock {

$AppName = $args[0]

$AppVersion = $args[1]

if ([IntPtr]::Size -eq 4) {

$regpath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'

}

else {

$regpath = @(

'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'

'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'

)

}

$InstalledApps = Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} |

Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |

Sort DisplayName

If ($AppVersion -ne "all"){

Return $InstalledApps | where {$_.DisplayName -eq $AppName -and $_.DisplayVersion -eq $AppVersion}

}

Else{

Return $InstalledApps | where {$_.DisplayName -eq $AppName}

}

} -ArgumentList $AppName, $AppVersion -Credential $Cred

}catch{throw $_.Exception}

}

else{

try{

Return Invoke-Command -computername $Computer -ScriptBlock {

$AppName = $args[0]

$AppVersion = $args[1]

if ([IntPtr]::Size -eq 4) {

$regpath = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'

}

else {

$regpath = @(

'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'

'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'

)

}

$InstalledApps = Get-ItemProperty $regpath | .{process{if($_.DisplayName -and $_.UninstallString) { $_ } }} |

Select DisplayName, Publisher, InstallDate, DisplayVersion, UninstallString |

Sort DisplayName

If ($AppVersion -ne "all"){

Return $InstalledApps | where {$_.DisplayName -eq $AppName -and $_.DisplayVersion -eq $AppVersion}

}

Else{

Return $InstalledApps | where {$_.DisplayName -eq $AppName}

}

} -ArgumentList $AppName, $AppVersion

}catch{throw $_.Exception}

}

}

Function CheckWMIQuery([string]$Computer){

If ($Cred){

try{

Return Invoke-Command -computername $Computer -ScriptBlock {

$WMIQuery = $args[0]

Write-Host "Executing $($WMIQuery)"

Return gwmi -Query $WMIQuery

} -ArgumentList $WMIQuery -Credential $Cred

}catch{throw $_.Exception}

}

else{

try{

Return Invoke-Command -computername $Computer -ScriptBlock {

$WMIQuery = $args[0]

Write-Host "Executing $($WMIQuery)"

Return gwmi -Query $WMIQuery

} -ArgumentList $WMIQuery

}catch{throw $_.Exception}

}

}

Function InstallRemoteSoftware([string]$Computer){

If ($Cred){

try{

Return Invoke-Command -computername $Computer -ScriptBlock {

$Application = $args[0]

$AppArgs = $args[1]

$ApplicationName = $Application.Substring($Application.LastIndexOf('\')+1)

$ApplicationFolderPath = $Application.Substring(0,$Application.LastIndexOf('\'))

$ApplicationExt = $Application.Substring($Application.LastIndexOf('.')+1)

Write-Host "Installing $($ApplicationName) on $($env:COMPUTERNAME)"

If($ApplicationExt -eq "msi"){

If ($AppArgs -ne "None"){

Write-Host "Installing as MSI: msiexec /i $($Application) $($AppArgs)"

$p = Start-Process "msiexec" -ArgumentList "/i $($Application) $($AppArgs)" -Wait -Passthru

}

else{

Write-Host "Installing as MSI: msiexec /i $($Application)"

$p = Start-Process "msiexec" -ArgumentList "/i $($Application) /quiet /norestart" -Wait -Passthru

}

}

ElseIf ($AppArgs -ne "None"){

Write-Host "Executing $Application $AppArgs"

$p = Start-Process $Application -ArgumentList $AppArgs -Wait -Passthru

}

Else{

Write-Host "Executing $Application"

$p = Start-Process $Application -Wait -Passthru

}

$p.WaitForExit()

if ($p.ExitCode -ne 0) {

Write-Host "Failed installing with error code $($p.ExitCode)" -ForegroundColor Red

$Return = $($env:COMPUTERNAME)

}

else{

$Return = 0

}

Write-Host "Deleting $($ApplicationFolderPath)"

Remove-Item $($ApplicationFolderPath) -Force -Recurse

Return $Return

} -ArgumentList "$($LocalPath)\$($ApplicationFolderName)\$($ApplicationName)", $AppArgs -Credential $Cred

}catch{throw $_.Exception}

}

else{

try{

Return Invoke-Command -computername $Computer -ScriptBlock {

$Application = $args[0]

$AppArgs = $args[1]

$ApplicationName = $Application.Substring($Application.LastIndexOf('\')+1)

$ApplicationFolderPath = $Application.Substring(0,$Application.LastIndexOf('\'))

$ApplicationExt = $Application.Substring($Application.LastIndexOf('.')+1)

Write-Host "Installing $($ApplicationName) on $($env:COMPUTERNAME)"

If($ApplicationExt -eq "msi"){

If ($AppArgs -ne "None"){

Write-Host "Installing as MSI: msiexec /i $($Application) $($AppArgs)"

$p = Start-Process "msiexec" -ArgumentList "/i $($Application) $($AppArgs)" -Wait -Passthru

}

else{

Write-Host "Installing as MSI: msiexec /i $($Application)"

$p = Start-Process "msiexec" -ArgumentList "/i $($Application) /quiet /norestart" -Wait -Passthru

}

}

ElseIf ($AppArgs -ne "None"){

Write-Host "Executing $Application $AppArgs"

$p = Start-Process $Application -ArgumentList $AppArgs -Wait -Passthru

}

Else{

Write-Host "Executing $Application"

$p = Start-Process $Application -Wait -Passthru

}

$p.WaitForExit()

if ($p.ExitCode -ne 0) {

Write-Host "Failed installing with error code $($p.ExitCode)" -ForegroundColor Red

$Return = $($env:COMPUTERNAME)

}

else{

$Return = 0

}

Write-Host "Deleting $($ApplicationFolderPath)"

Remove-Item $($ApplicationFolderPath) -Force -Recurse

Return $Return

} -ArgumentList "$($LocalPath)\$($ApplicationFolderName)\$($ApplicationName)", $AppArgs

}catch{throw $_.Exception}

}

}

Function CheckPSRemoting([string]$Computer){

If ($EnablePSRemoting){

Set-Message "Enabling PSRemoting on computer: psexec.exe /accepteula -h -d \\$($Computer) -s powershell Enable-PSRemoting"

try{

psexec.exe /accepteula -h -d "\\$($Computer)" -s powershell Enable-PSRemoting -Force 2>&1 | Out-Null

}catch{

Set-Message "PSExec running on background. Continue with next computer."

}

}

Else{

Set-Message "You can try to enable PowerShell Remoting on computer using parameter -EnablePSRemoting" -ForegroundColor DarkYellow

}

}

$ErrorActionPreference = "Stop"

#Initialice log

$LogPath += "\InstallSoftwareRemotely_" + $(get-date -Format "yyyy-mm-dd_hh-mm-ss") + ".txt"

Set-Message "Start remote installation on $(get-date -Format "yyyy-mm-dd hh:mm:ss")" -Append $False

#Initial validations.

If (!(Test-Path $AppPath)){

Set-Message "Error accessing $($AppPath). The script can not continue"

Exit 1

}

If ($EnablePSRemoting){

if (!(Get-Command "psexec.exe" -ErrorAction SilentlyContinue)){

Set-Message "Error. Microsoft Psexec not found on system. Download it from https://download.sysinternals.com/files/PSTools.zip and extract all in C:\Windows\System32" -ForegroundColor Yellow

$Answer=Read-Host "Do you want to download and install PSTools (y/n)?"

if (($Answer -eq "y") -or ($Answer -eq "Y")){

Set-Message "Downloading PSTools"

If (Test-Path "$($env:temp)\PSTools.zip"){

Remove-Item "$($env:temp)\PSTools.zip" -Force

}

(New-Object System.Net.WebClient).DownloadFile("https://download.sysinternals.com/files/PSTools.zip", "$($env:temp)\PSTools.zip")

if (Test-Path "$($env:temp)\PSTools.zip"){

Set-Message "Unzipping PSTools"

If (Test-Path "$($env:temp)\PSTools"){

Remove-Item "$($env:temp)\PSTools" -Force -Recurse

}

Unzip "$($env:temp)\PSTools.zip" "$($env:temp)\PSTools"

Copy-Item "$($env:temp)\PSTools\*.exe" "$($env:SystemRoot)\System32" -Force

if (Test-Path "$($env:SystemRoot)\System32\psexec.exe"){

Set-Message "PSTools installed" -ForegroundColor Green

}

else{

Set-Message "Error unzipping PSTools" -ForegroundColor Red

Remove-Item "$($env:temp)\PSTools.zip" -Force

Exit 1

}

}

else{

Set-Message "Error downloading PSTools" -ForegroundColor Red

Exit 1

}

}

else{

Exit 1

}

}

}

If ($OU){

if (!(Get-Command "Get-ADComputer" -ErrorAction SilentlyContinue)){

Set-Message "Error. Get-ADComputer not found on system. You have to install the PowerShell Active Directory module order to query Active Directory. https://4sysops.com/archives/how-to-install-the-powershell-active-directory-module/" -ForegroundColor Red

Exit 1

}

try{

$ComputerList = Get-ADComputer -Filter * -SearchBase "$OU" | Select-Object -Expand name

}catch{

Set-Message "Error querying AD: $($_.Exception.Message)" -ForegroundColor Red

Exit 1

}

}

ElseIf ($CSV){

try{

$ComputerList = Get-Content $CSV | where {$_ -notmatch 'Name'} | Foreach-Object {$_ -replace '"', ''}

}catch{

Set-Message "Error getting CSV content: $($_.Exception.Message)" -ForegroundColor Red

Exit 1

}

}

ElseIf(!$ComputerList){

Set-Message "You have to set a list of computers, OU or CSV." -ForegroundColor Red

Exit 1

}

If ($Credential){

$Cred = Get-Credential

}

If(!$Cred -or !$Credential){

Set-Message "No credential specified. Using logon account"

}

Else{

Set-Message "Using user $($Cred.UserName)"

}

$ApplicationName = $AppPath.Substring($AppPath.LastIndexOf('\')+1)

$ApplicationFolderPath = $AppPath.Substring(0,$AppPath.LastIndexOf('\'))

$ApplicationFolderName = $ApplicationFolderPath.Substring($ApplicationFolderPath.LastIndexOf('\')+1)

$ComputerWithError = [System.Collections.ArrayList]@()

$ComputerWithSuccess = [System.Collections.ArrayList]@()

$ComputerSkipped = [System.Collections.ArrayList]@()

$TotalRetries = $Retries

$TotalComputers = $ComputerList.Count

Do{

Set-Message "-----------------------------------------------------------------"

Set-Message "Attempt $(($TotalRetries - $Retries) +1) of $($TotalRetries)" -ForegroundColor Cyan

Set-Message "-----------------------------------------------------------------"

$Count = 1

ForEach ($Computer in $ComputerList){

Set-Message "COMPUTER $($Computer.ToUpper()) ($($Count) of $($ComputerList.Count))" -ForegroundColor Yellow

$Count++

If($AppName -ne "None"){

Set-Message "Checking if $($AppName) version $($AppVersion) is installed on remote computer."

try{

If(CheckSoftwareInstalled $Computer){

Set-Message "Software found on computer. Skipping installation." -ForegroundColor Green

$ComputerSkipped.Add($Computer) | Out-Null

Continue

}

Else{

Set-Message "Software not found on remote computer."

}

}catch{

Set-Message "Error connecting: $($_.Exception.Message)" -ForegroundColor Red

CheckPSRemoting $Computer

$ComputerWithError.Add($Computer) | Out-Null

Continue

}

}

If($WMIQuery -ne "None"){

Set-Message "Checking WMI Query on remote computer."

try{

If(!(CheckWMIQuery $Computer)){

Set-Message "WMI Query result is false. Skipping installation."

$ComputerSkipped.Add($Computer) | Out-Null

Continue

}

Else{

Set-Message "WMI Query result is true. Continue installation."

}

}catch{

Set-Message "Error connecting: $($_.Exception.Message)" -ForegroundColor Red

CheckPSRemoting $Computer

$ComputerWithError.Add($Computer) | Out-Null

Continue

}

}

Set-Message "Coping $($ApplicationFolderPath) to \\$($Computer)\$($LocalPath -replace ':','$')"

try{

Copy-WithProgress "$ApplicationFolderPath" "\\$($Computer)\$("$($LocalPath)\$($ApplicationFolderName)" -replace ':','$')"

}catch{

Set-Message "Error copying folder: $($_.Exception.Message)" -ForegroundColor Red

$ComputerWithError.Add($Computer) | Out-Null

Continue;

}

try{

$ExitCode = InstallRemoteSoftware $Computer

If ($ExitCode){

$ComputerWithError.Add($Computer) | Out-Null

Set-Message "Error installing $($ApplicationName)." -ForegroundColor Red

}

else{

Set-Message "$($ApplicationName) installed successfully." -ForegroundColor Green

$ComputerWithSuccess.Add($Computer) | Out-Null

}

}catch{

Set-Message "Error on remote execution: $($_.Exception.Message)" -ForegroundColor Red

$ComputerWithError.Add($Computer) | Out-Null

try{

Set-Message "Deleting \\$($Computer)\$($LocalPath -replace ':','$')\$($ApplicationFolderName)"

}catch{

Set-Message "Error on remote deletion: $($_.Exception.Message)" -ForegroundColor Red

}

Remove-Item "\\$($Computer)\$($LocalPath -replace ':','$')\$($ApplicationFolderName)" -Force -Recurse

CheckPSRemoting $Computer

}

}

If ($ComputerWithError.Count -eq 0){

break

}

$Retries--

If ($Retries -gt 0){

$ComputerList=$ComputerWithError

$ComputerWithError = [System.Collections.ArrayList]@()

If ($TimeBetweenRetries -gt 0){

Set-Message "Waiting $($TimeBetweenRetries) seconds before next retry..."

Sleep $TimeBetweenRetries

}

}

}While ($Retries -gt 0)

If($ComputerWithError.Count -gt 0){

Set-Message "-----------------------------------------------------------------"

Set-Message "Error installing $($ApplicationName) on $($ComputerWithError.Count) of $($TotalComputers) computers:"

Set-Message $ComputerWithError

$csvContents = @()

ForEach($Computer in $ComputerWithError){

$row = New-Object System.Object

$row | Add-Member -MemberType NoteProperty -Name "Name" -Value $Computer

$csvContents += $row

}

$CSV=(get-date).ToString('yyyyMMdd-HH_mm_ss') + "ComputerWithError.csv"

$csvContents | Export-CSV -notype -Path "$([Environment]::GetFolderPath("MyDocuments"))\$($CSV)" -Encoding UTF8

Set-Message "Computers with error exported to CSV file: $([Environment]::GetFolderPath("MyDocuments"))\$($CSV)" -ForegroundColor DarkYellow

Set-Message "You can retry failed installation on this computers using parameter -CSV $([Environment]::GetFolderPath("MyDocuments"))\$($CSV)" -ForegroundColor DarkYellow

}

If ($ComputerWithSuccess.Count -gt 0){

Set-Message "-----------------------------------------------------------------"

Set-Message "$([math]::Round((($ComputerWithSuccess.Count * 100) / $TotalComputers), [System.MidpointRounding]::AwayFromZero) )% Success installing $($ApplicationName) on $($ComputerWithSuccess.Count) of $($TotalComputers) computers:"

Set-Message $ComputerWithSuccess

}

Else{

Set-Message "-----------------------------------------------------------------"

Set-Message "Installation of $($ApplicationName) failed on all computers" -ForegroundColor Red

}

If ($ComputerSkipped.Count -gt 0){

Set-Message "-----------------------------------------------------------------"

Set-Message "$($ComputerSkipped.Count) skipped of $($TotalComputers) computers:"

Set-Message $ComputerSkipped

}

Monday, February 4, 2019

Unable to install Service Pack 1 onto Windows Server 2008 R2

Problem

You have a Windows Server 2008 R2 server that currently does not have SP1 installed:

You proceed to download Windows Server 2008 R2 SP1 and run the install:

windows6.1-KB976932-X64.exe

… but it fails with the following error message:

Installation was not successful

An unknown error has occurred. (Details)

Error: 0x800f0818

Reviewing the CBS.log log located in the directory:

C:\Windows\Logs\CBS

Reveals the following error messages:

2019-01-25 15:16:10, Info CBS Mark store corruption flag because there is a mismatch between package identity and its content on package: Package_for_KB2618444_RTM~31bf3856ad364e35~amd64~~6.1.1.2. [HRESULT = 0x00000000 - S_OK]

2019-01-25 15:16:10, Info CBS Identity mismatch: Specified Identity: Package_for_KB2618444_RTM~31bf3856ad364e35~amd64~~6.1.1.2, actual package Identity: Microsoft-Windows-Foundation-Package~31bf3856ad364e35~amd64~~6.1.7600.16385 [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to resolve package [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to populate children. [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to initialize package: Microsoft-Windows-InternetExplorer-Package~31bf3856ad364e35~amd64~~8.0.7600.16385, from path: \\?\C:\Windows\Servicing\Packages\Microsoft-Windows-InternetExplorer-Package~31bf3856ad364e35~amd64~~8.0.7600.16385.mum, existing package: 1 [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to resolve package [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to populate children. [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to initialize internal package [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Info CBS Failed to create package. [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Error CBS Failed to internally open package. [HRESULT = 0x800f0818 - CBS_E_IDENTITY_MISMATCH]

2019-01-25 15:16:10, Error CBS SPI: (CSPICbsClient::EnumPackages:156)Failed to open package hr=0x800f0818

2019-01-25 15:16:10, Error CBS SPI: (CSystem::EnumerateCbsPackages:360)Failed to populate CBS package list hr=0x800f0818

2019-01-25 15:16:10, Info CBS Session: 30717154_1779796761 finalized. Reboot required: no [HRESULT = 0x00000000 - S_OK]

2019-01-25 15:16:10, Info CBS SPI: Failed enumerating CBS packages

2019-01-25 15:16:10, Error CBS SPI: (GetLatestVersionFromCBSStore:131)ATL exception hr=0x800f0818

2019-01-25 15:16:10, Error CBS SPI: (CSPCInstallTask::ApplicabilityScan:632)Failed to get latest version of Package_for_KB976902~31bf3856ad364e35~amd64~~6.1.1.17514 from the store hr=0x800f0818

2019-01-25 15:16:10, Error CBS SPI: (CSPInstall::CompatibilityApplicabilityScan:1303)Failed in applicability check of task hr=0x800f0818

2019-01-25 15:16:10, Info CBS SPI: Ending Compatibility\Applicability scan

2019-01-25 15:16:10, Error CBS SPI: (PerformSPInstallation:833)Failed to install SP using UI hr=0x800f0818

2019-01-25 15:16:10, Error CBS SPI: (wmain:1105)Failed to perform SP installation hr=0x800f0818

2019-01-25 15:16:10, Info CBS SPI: Reporting Failed event

You navigate the directory C:\Windows\servicing\Packages and can confirm that the Package_for_KB2618444_RTM~31bf3856ad364e35~amd64~~6.1.1.2. exists.

Searching for this error message results in recommendations to install the:

System Update Readiness Tool for Windows Server 2008 R2 x64 Edition (KB947821) [October 2014]

https://www.microsoft.com/en-us/download/details.aspx?id=14668

Windows6.1-KB947821-v34-x64.msu

You proceed to install the package:

Then attempt to install SP1 again but now receive the following error:

Installation was not successful

A required certificate is not twithin its validity period when verifying against the current system clock or the timestampe in the signed file.

Error: CERT_E_EXPIRED(0x800b0101)

Proceeding to review the SP1 install logs reveal the following:

2019-01-25 15:58:21, Info CBS WinVerifyTrust failed [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Error CBS Failed to verify if catalog file \\?\C:\Windows\Servicing\Packages\Package_15_for_KB2722913~31bf3856ad364e35~amd64~~6.1.1.0.cat is valid. [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to initialize package: Package_15_for_KB2722913~31bf3856ad364e35~amd64~~6.1.1.0, from path: \\?\C:\Windows\Servicing\Packages\Package_15_for_KB2722913~31bf3856ad364e35~amd64~~6.1.1.0.mum, existing package: 1 [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to resolve package [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to populate children. [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to initialize package: Microsoft-Windows-InternetExplorer-Package~31bf3856ad364e35~amd64~~8.0.7600.16385, from path: \\?\C:\Windows\Servicing\Packages\Microsoft-Windows-InternetExplorer-Package~31bf3856ad364e35~amd64~~8.0.7600.16385.mum, existing package: 1 [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to resolve package [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to populate children. [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to initialize internal package [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Info CBS Failed to create package. [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Error CBS Failed to internally open package. [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

2019-01-25 15:58:21, Error CBS SPI: (CSPICbsClient::EnumPackages:156)Failed to open package hr=0x800b0101

2019-01-25 15:58:21, Error CBS SPI: (CSystem::EnumerateCbsPackages:360)Failed to populate CBS package list hr=0x800b0101

2019-01-25 15:58:21, Info CBS Session: 30717160_1382002389 finalized. Reboot required: no [HRESULT = 0x00000000 - S_OK]

2019-01-25 15:58:21, Info CBS SPI: Failed enumerating CBS packages

2019-01-25 15:58:21, Error CBS SPI: (GetLatestVersionFromCBSStore:131)ATL exception hr=0x800b0101

2019-01-25 15:58:21, Error CBS SPI: (CSPCInstallTask::ApplicabilityScan:632)Failed to get latest version of Package_for_KB976902~31bf3856ad364e35~amd64~~6.1.1.17514 from the store hr=0x800b0101

2019-01-25 15:58:21, Error CBS SPI: (CSPInstall::CompatibilityApplicabilityScan:1303)Failed in applicability check of task hr=0x800b0101

2019-01-25 15:58:21, Info CBS SPI: Ending Compatibility\Applicability scan

2019-01-25 15:58:21, Error CBS SPI: (PerformSPInstallation:833)Failed to install SP using UI hr=0x800b0101

2019-01-25 15:58:21, Error CBS SPI: (wmain:1105)Failed to perform SP installation hr=0x800b0101

2019-01-25 15:58:21, Info CBS SPI: Reporting Failed event

Further research shows that rolling back the clock would allow for the install:

CERT_E_EXPIRED(0x800b0101)

https://social.technet.microsoft.com/Forums/Lync/en-US/5c95bd6f-041e-4d68-b19b-304c5162aa27/certeexpired0x800b0101?forum=w7itproSP

Doing so did not work for this situation. A bit more digging in the logs revealed this line referencing this package:

2019-01-25 14:50:28, Info CBS Read out cached package applicability for package: WUClient-SelfUpdate-Core-TopLevel~31bf3856ad364e35~amd64~~7.6.7600.256, ApplicableState: 112, CurrentState:112

Locating the file and opening the package confirmed that the WUClient-SelfUpdate-Core~31bf3856ad364e35~amd64~~7.6.7600.256.cat had a timestamp dating back to June 2, 2012 (it’s 2019 right now):

Another line in the logs that actually referenced a certificate was the following:

CBS Failed to verify if catalog file \\?\C:\Windows\Servicing\Packages\Package_15_for_KB2722913~31bf3856ad364e35~amd64~~6.1.1.0.cat is valid. [HRESULT = 0x800b0101 - CERT_E_EXPIRED]

Locating this package and viewing its properties confirmed that the Digital Signature had expired on June 28, 2012:

Solution

It took a bit of time but the solution to this issue was to install the following update to correct the signatures before installing SP1:

Microsoft Security Advisory: Compatibility issues affecting signed Microsoft binaries: November 13, 2012

https://support.microsoft.com/en-us/help/2749655/microsoft-security-advisory-compatibility-issues-affecting-signed-micr