How can I find the Upgrade Code for an installed MSI file?

To satisfy your requirements for using WMI directly, or for those times you just need a one-off without Powershell (or need to use .bat or whatever), use wmic:

    C:\>wmic product list brief
    Caption                                                                                              IdentifyingNumber                       Name                                                                                                 Vendor                          Version
        Sourcetree                                                                                           {1B05DFFD-1DB9-48CD-9265-F3976512A579}  Sourcetree                                                                                           Atlassian                       2.6.10.0
        Microsoft Office Access database engine 2007 (English)                                               {90120000-00D1-0409-0000-0000000FF1CE}  Microsoft Office Access database engine 2007 (English)                                               Microsoft Corporation           12.0.4518.1031
        Office 16 Click-to-Run Extensibility Component                                                       {90160000-008C-0000-0000-0000000FF1CE}  Office 16 Click-to-Run Extensibility Component    

There are multiple formatting and output options.


MSI Upgrade Code Retrieval (via PowerShell / WMI)

UPDATE: HTML Export VBScript - screenshot section 2 here.

Uninstalling?: Uninstall via Upgrade or Productcode, Via Product Name, etc...

The PowerShell script below should retrieve all related product codes, upgrade codes and product names installed on your machine (table output).

Screenshot of output (full script below):

powershell output

These are the real, live values directly from the Windows Installer database on the machine in question. There is no need for any conversion or interpretation. We are going through the proper APIs.

Technical note!: Be aware that checking properties directly in your original MSI file (property table) or WiX source file, may not match actual installed values since properties can be overridden at install time via transforms (more info below) - or property values specified at the command line. The moral of the story: retrieve property values directly from the system when you can.

Quick disclaimer: In rare cases running the script can trigger a Windows Installer self-repair. Read more in "disclaimer section" below. Just a potential nuisance, but read the disclaimer please.

As a digression, there is also a one-line PowerShell command which will retrieve product codes and upgrade codes only - without the package name included. This might actually suffice for some users (I would recommend the full script below however). There is a screenshot of the output of this one-liner in a section below. Note: this command appears a lot faster than the larger script (the "Value" field is the upgrade code). Also note: product codes without associated upgrade codes will not show up as far as I can tell - they will in the larger script:

gwmi -Query "SELECT ProductCode,Value FROM Win32_Property WHERE Property='UpgradeCode'" | Format-Table ProductCode,Value

To run the full PowerShell script below:

  1. Launch PowerShell (hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK or hit enter).
  2. Copy the script below in its entirety, and then just right click inside the PowerShell window.
  3. This should start the script, and it will take quite a while to run.
  4. Please report any problems. I am no PowerShell expert - I am a deployment specialist not a coder, but the script should do the job.
  5. Performance note: I just get the whole Win32_Product WMI object
    • Cherry picking properties seemed to actually make it marginally slower (VBScript test).
    • I guess we need to get all rows anyway, and cherry picking columns is just extra lifting?
    • For Win32_Property we filter both rows and columns (upgrade code is just one of many row-types). Be prepared for a slow operation, WMI is very slow.
$wmipackages = Get-WmiObject -Class win32_product
$wmiproperties = gwmi -Query "SELECT ProductCode,Value FROM Win32_Property WHERE Property='UpgradeCode'"
$packageinfo = New-Object System.Data.Datatable
[void]$packageinfo.Columns.Add("Name")
[void]$packageinfo.Columns.Add("ProductCode")
[void]$packageinfo.Columns.Add("UpgradeCode")

foreach ($package in $wmipackages) 
{
    $foundupgradecode = $false # Assume no upgrade code is found

    foreach ($property in $wmiproperties) {

        if ($package.IdentifyingNumber -eq $property.ProductCode) {
           [void]$packageinfo.Rows.Add($package.Name,$package.IdentifyingNumber, $property.Value)
           $foundupgradecode = $true
           break
        }
    }
    
    if(-Not ($foundupgradecode)) { 
         # No upgrade code found, add product code to list
         [void]$packageinfo.Rows.Add($package.Name,$package.IdentifyingNumber, "") 
    }
}

$packageinfo | Sort-Object -Property Name | Format-table ProductCode, UpgradeCode, Name

# Enable the following line to export to CSV (good for annotation). Set full path in quotes
# $packageinfo | Export-Csv "[YourFullWriteablePath]\MsiInfo.csv"

# copy this line as well

Running on Remote Machines

  • It should be relatively easy to extend the script above to run on remote machines, but I am not set up to test it properly at the moment.
  • The information below has gotten a bit messy, let me know if it is not understandable or unclear.
  • In a real Windows domain it should (in theory) just be a matter of adding the remote machines to the WMI calls themselves (and loop over a list of machines - see mock-up below). And crucially: you should use a real domain admin account to run the query. It is possible that the changes I list below to make WMI work in workgroup environments also could be required for some domains, I don't know (firewall rule and UAC registry tweak). I would guess that a real domain admin account should have the privileges and access required though.
  • Remote connections in WMI are affected by (at least) the Windows Firewall, DCOM settings, CIMOM Settings and User Account Control (UAC) (plus any additional non-Microsoft factors - for instance real firewalls, third party software firewalls, security software of various kinds, etc...). Here are some details:
    • Setting up a Remote WMI Connection
    • Connecting to WMI Remotely with PowerShell
  • In non-domain networks (small office, home, etc...) you probably have to add user credentials directly to the WMI calls to make it work. And you probably must have "real admin rights" on the machines in question to make the queries run remotely in a home network (workgroup). I have heard that the built-in Administrator account does not have any UAC issues, but I have never tried it. In my opinion: don't use this account.
    • In my testing I had to (1) update the Windows firewall rules and (2) disable the Remote UAC access token filtering and use a real, local admin account on the remote system. Note that I don't recommend either of these changes, just reporting what worked for me.
    • Change 1: Windows Firewall, run command (cmd.exe, run as admin): netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes (source - see this link for command line to disable this new rule again if you are just testing. Essentially just set enable=no). See the linked source for potentially more restrictive rules that could also work.
    • Change 2: Disable Remote UAC access token filtering: you need to set the following registry value: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\ LocalAccountTokenFilterPolicy = 1 (source - mid page, latter half). I set a 32-bit DWORD.

With those changes in place on the remote system, I also added user credentials to each call by prompting the user $Cred = Get-Credential. There are also more advanced options for defining the user credentials, as explained here: Pass password into -credential (and here). To test run, here is a little test script. Copy all lines below, modify the remote machine name and paste into PowerShell by right clicking (you will be prompted for credentials):

$Cred = Get-Credential
gwmi -ComputerName RemoteMachineName -credential $Cred -Query "SELECT ProductCode,Value FROM Win32_Property WHERE Property='UpgradeCode'" | Format-Table ProductCode,Value
# copy this line too

For the large PowerShell script above, the basic additions for remote running on several machines in a Windows domain, could be something like this (I won't update the above script since I can't really test this properly). Remember to update the list of remote computer names at the top of the script and run with a domain admin account:

# DOMAIN NETWORK: mock-up / pseudo snippet ONLY - lacks testing, provided "as is"
$ArrComputers = "Computer1", "Computer2", "Computer3"
foreach ($Computer in $ArrComputers) 
{
    # here we modify the WMI calls to add machine name
    $wmipackages = Get-WmiObject -Class win32_product -ComputerName $Computer
    $wmiproperties = gwmi  -ComputerName $Computer -Query "SELECT ProductCode,Value FROM Win32_Property WHERE Property='UpgradeCode'"

    # the rest of the above, large script here (minus the first 2 WMI lines)
}

To adapt the same machine loop for a non-domain network you can add credentials to the WMI calls. Something like this (you will be prompted for credentials for each machine - which might be confusing). Remember to update the list of remote computer names at the top of the script and use an account with local admin rights on the target box:

# WORKGROUP NETWORK: mock-up / pseudo snippet ONLY - lacks testing, provided "as is"
$ArrComputers = "Computer1", "Computer2", "Computer3"
foreach ($Computer in $ArrComputers) 
{
     $Cred = Get-Credential

     # here we modify the WMI calls to add machine name AND credentials
     $wmipackages = Get-WmiObject -Class win32_product -ComputerName $Computer -credential $cred
     $wmiproperties = gwmi  -ComputerName $Computer -credential $cred -Query "SELECT ProductCode,Value FROM Win32_Property WHERE Property='UpgradeCode'"

     # the rest of the above, large script here (minus the first 2 WMI lines) 
}

The real answer ends here. I believe the above newer script should cover most use-cases, but I will leave the content below as well since it is not obsolete, just probably less efficient than the above script. Reading it will probably be repetitious.

The scripts below for retrieval of single upgrade codes rather than the whole list, could be of interest if you want to retrieve a single upgrade code from within your own application at run-time. I'll leave that older content in.

Disclaimer: The above script uses WMI, and when you access the class Win32_Product it triggers an integrity check of installed packages. This is quite slow, and can in very special cases trigger an MSI self-repair. This is not good if you are heading into an important meeting :-). Luckily you should be able to cancel any triggered self-repairs (but your query will probably not complete until you let the repair finish). Quick context link (for safekeeping).

IMHO: don't let this stop you from using WMI - it is just an annoyance. Note: both the PowerShell and VBScript approaches described below use WMI and can trigger this issue as well.


Retrieving Upgrade Codes For MSI Files That Are Not Installed

If you need the upgrade code for an MSI package that is not installed on your machine, please read the "Manual Retrieval of Upgrade Codes" section towards the bottom for several options (essentially look in the MSI file itself, or its source file used to compile it).

It is not safe to get the upgrade code for installed packages from the original MSI install file itself or from the (WiX) sources used to compile the MSI, because upgrade codes can be overridden at install time using transforms (details in text below - transforms are little database fragments applied at install time, see that Symantec link for details).

The programmatic retrieval of upgrade codes relies on WMI, and you can use either PowerShell or VBScript to invoke WMI. Both methods are presented below. Essentially the following WMI query is run to retrieve the upgrade code for a specified product code:

SELECT * FROM Win32_Property WHERE Property='UpgradeCode' AND ProductCode='{YourProdGuid}'

It is the same query used for both VBScript and PowerShell. You can also run it as a straight WMI query using a tool such as as WMIExplorer.exe. A very useful tool - highly recommended. I believe this is their site: https://github.com/vinaypamnani/wmie2/releases


Retrieve Single Upgrade Code Via PowerShell / WMI

Rather than outputting a whole table with all product codes and upgrade codes, you can retrieve a single upgrade code for a specified product code. This is good if you are trying to do the retrieval from inside your own application code (then it is just a standard WMI query and has nothing to do with PowerShell).

Below is the single upgrade code retrieval done via PowerShell (to launch PowerShell: hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK or hit enter):

gwmi -Query "SELECT Value FROM Win32_Property WHERE Property='UpgradeCode' AND ProductCode='{YourGuid}'" | Format-Table Value

The output should be something like this (maybe a little hard to read, I should have used larger fonts):

Retrieving upgrade code using PowerShell - annotated

The product code specified in the query above is for "Windows SDK Intellidocs". You must obviously replace it with your own product code guid. To find the product code you need to pass in, you can also use a PowerShell query as described here: How can I find the product GUID of an installed MSI setup?

The returned upgrade code is coming straight from the real Windows Installer registry database. It requires no further processing or interpretation or manual conversion steps. It will also be correct, even if a transform changed the original upgrade code when the MSI was installed (details on transform issues below).

Update, special notice: Without complicating things unnecessarily, I believe I have found a bug in WMI that is very specific. When an original MSI has no upgrade code set, and you add one via a transform, then WMI does not seem to report the upgrade code at all. However: if the original MSI has an upgrade code, and you override it in a transform, WMI reports the transform's upgrade code (which is expected). I definitely saw this, but will need to verify with one more test package to be sure. The moral of the story: always set an upgrade code in your MSI! Then you avoid the whole issue permanently. And don't auto-generate it - hard code it (read "Manual Retrieval of Upgrade Codes" below for an explanation).


Retrieve Single upgrade code using VBScript / WMI (Legacy Approach)

There is nothing wrong with the VBScript solution found below - it even has some benefits over PowerShell - despite VBScript being a legacy technology by now. The benefits are that it should work on all machines, even when the .NET framework is missing (or locked), and on machines where PowerShell is missing (or locked). It is a dated, but viable solution that is quite flexible (unless VBScript is also locked, but all modern OS versions fully support VBScript).

In order to make it as simple as possible to retrieve your upgrade code, I have created a "bare-bone VBScript" which should do the trick. It has not been tested for targeting remote computers, even if WMI should be able to do so by design. The script is intended to be run on the system where your mystery MSI with the unknown upgrade code is installed.

This VBScript requires an input product code (input dialog shown when script is run), and it will then proceed to look up the corresponding upgrade code (if any). As stated above, to locate the product code for your MSI, you can use this approach: How can I find the product GUID of an installed MSI setup?. Once you have the product code (guid), you can run this VBScript on the target machine and you should get the upgrade code returned to you in a few seconds. WMI retrieval can be very slow.

'
' Purpose: Barebone / minimal VBScript implementation to allow retrieval of MSI UpgradeCodes via WMI.
'
' Version: 0.2, September.2017 - Stein Åsmul.
'
' Notes:
'
'  - As it stands, this script is intended to be run interactively (WScript).
'  - Conversion to run via CScript should be trivial (nothing ever is...)
'  - The script will ask the user to provide a valid product GUID for an installed MSI.
'  - To find a valid product GUID for your system, perhaps see this SO answer: https://stackoverflow.com/a/29937569/129130
'  - The script does not RegEx anything to check for valid GUID format (this is barebone - as terse as possible,
'    with as little as possible included that can break).
'
' UPDATE: for information on remote running, check "Running on remote machines" section here:
' https://stackoverflow.com/a/46637095/129130 (firewall and registry change seems to be needed).

strComputer = "."
' Remote connections was NOT tested for this script. In principle you should just add the machine name to "strComputer" above.
' AFAIK you must have "real" admin rights on the box you try to connect to. Many users report intermittent problems running remote WMI.
' Remote connections in WMI are affected by the Windows Firewall, DCOM settings, and User Account Control (UAC).
'    - Setting up a Remote WMI Connection: https://msdn.microsoft.com/en-us/library/aa822854(v=vs.85).aspx
'    - Connecting to WMI on a Remote Computer: https://msdn.microsoft.com/en-us/library/aa389290(v=vs.85).aspx
'    - Perhaps useful: https://social.technet.microsoft.com/Forums/lync/en-US/05205b52-0e43-4ce3-a8b8-58ec4c2edea5/wmi-generic-failure-when-accessing-win32product-remotely?forum=winserverManagement
'    - Maybe it is also worth noting that I think WMI queries can be slow enough to trigger timeouts,
'      and then you have the old favorite: intermittent bugs.

Set owmi = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

' User interaction
productcode = InputBox("Please paste or type in the product code for the product whose upgrade code you want " + _
                       "to retrieve (not case sensitive, a blank product code will abort the script)." + vbNewLine + vbNewLine + _
                       "Please note that the script can take up to a minute to run due to WMI's slowness.", "UpgradeCode retrieval:")
If productcode = vbCancel Or Trim(productcode) = "" Then
   WScript.Quit(0)
End If

' Run WMI call and verify that it completes successfully.
On Error Resume Next
Set upgradecode = owmi.ExecQuery("SELECT Value FROM Win32_Property WHERE Property='UpgradeCode' AND ProductCode='" & productcode & "'")
If (Err.number <> 0) Then
   MsgBox "The WMI query failed, this is a critical error - aborting.", vbCritical, "Fatal error."
   WScript.Quit(2) ' Following exit code "standard" from MSI SDK automation samples
End If
On Error GoTo 0

' Report results.
Select Case upgradecode.count

   Case 0
       ' We have to provide a separate message for this state, since some packages may not have an UpgradeCode.
       ' However, the product GUID could also have been misspelled.
       MsgBox "No UpgradeCode was found, are you sure you entered the correct product GUID?" & vbNewLine & vbNewLine & _
              "Note: It is possible for a product to NOT have an UpgradeCode.", vbInformation, "No UpgradeCode found."

   Case 1
      ' The "default state" - should cover almost all normal packages.

      ' Only one upgrade code should have been retrieved, and it can be referenced by upgradecode.ItemIndex(0).Value on newer systems 
      ' (Vista and later), but on XP this apparently does not work (never tested by me), for compatibility we use a standard For Each 
      ' enumeration instead. Source: https://stackoverflow.com/questions/2378723/get-first-record-from-wmi-execquery

      For Each u in upgradecode
        Msgbox "The Upgrade Code is: " & u.Value & vbNewLine & vbNewLine & _
              "Just press CTRL + C to copy all text in this dialog (then paste to notepad or similar to extract the GUID).", _
              vbInformation, "UpgradeCode found."
          ' Exit For
      Next

   Case Else
       ' Should never get here - let us know if you do get this message.
       MsgBox "An error occurred, the query returned more than one result. There can only be one UpgradeCode. " & _ 
              "Please report this error on StackOverflow", vbInformation, "Error while retrieving UpgradeCode."
End Select

Retrieving All Upgrade Codes and Product Code on a Machine

I should mention that I have a large VBScript which will generate a comprehensive HTML report for all installed MSI packages on the machine it runs on. This includes all upgrade code and a list of related product codes (product codes that share the same upgrade code). However, I am not too happy with the code (I am a deployment specialist, not a coder). The script is too large, too slow and too untested for use, so I create the bare-bone VBScript found above to do retrieval for a single package only. This script is much easier to test and modify for your own use. I can provide this large VBScript for testing if of interest. It is read-only apart from a single HTML file output to "My Documents". It should be possible to adapt this script for use on remote computers as well.

There is a one-line PowerShell command to retrieve all product codes and related upgrade codes, but this output fill lack the name of the products. I include it here for completeness:

gwmi -Query "SELECT ProductCode,Value FROM Win32_Property WHERE Property='UpgradeCode'" | Format-Table ProductCode,Value

The output will be similar to this (the "Value" field is the upgrade code - product codes without associated upgrade codes will not show up as far as I can tell):

output of all upgrade codes and product codes


Manual Retrieval of Upgrade Codes

This section list some "manual ways" to retrieve upgrade codes that don't need any coding or command lines. These manual approaches are not the recommended ones. I include them only because this attempts to be a "reference answer". Several different options should be provided. My recommendation is to use the PowerShell or VBScript provided above.

That being said, upgrade codes should generally never change across versions of your product, so chances are you can try the one you find in the MSI file itself, or in the source used to compile it as described below. The problem that has already been mentioned several times is that a transform can change upgrade codes at install time, so you need to retrieve the upgrade code programatically if you want to be sure you find the correct one. Unless you are trying to get the upgrade code from an MSI that is not installed on your system. Then you just need a MSI file viewer as described below in bullet point 1.

A transform is just a database fragment with changes that are applied to the original MSI at install time. It is a tool mostly used for corporate application packaging to modify installers without modifying MSI files directly. Transforms have the extension .mst. Changing the upgrade code via a transform is unusual, but not unheard of - especially for corporate repackaging. In rare cases application packagers may intentionally change the upgrade guid to enable them to deliver their own upgrades to the packages installed (instead of relying on the vendor updates directly). Rare, but I have seen it done. Whether this is a good thing or not is highly debatable.

Easy, manual ways to find MSI upgrade codes:

  1. Though offensively obvious, the easiest way to find the upgrade code is to open the original MSI used to install the product and find the upgrade code in the Property table. All you need is a tool capable of opening MSI files. Here are some tools: What installation product to use? InstallShield, WiX, Wise, Advanced Installer, etc. Your fastest bet is probably Orca if you have Visual Studio installed (search for Orca-x86_en-us.msi and install it - this is Microsoft's own, official MSI viewer and editor), or Super Orca if you don't have Visual Studio installed (follow the above link to find it).

  2. If you are a developer using WiX (or any other deployment tool), you can obviously find the upgrade code easily in your WiX source file that you used to compile your MSI (or Installshield source, Advanced Installer source, or whatever deployment tool you are using).

    • Let's not fly off the handle here with too much well meant advice that clutters the main issue, but you should obviously hard code the upgrade code in your source, and never auto-generate it!
    • Upgrade codes define "families of related products" and should remain stable across releases (versions). In most cases it should remain stable across language versions as well. The exact setup depends on deployment requirements.
    • If products should be able to exist side-by-side you typically have different upgrade codes for the products that need to co-exist.
    • Rule of thumb: keep upgrade codes stable for as long as possible, whenever possible. Change them when requirements absolutely demand it.
    • To wrap things up: never use the same upgrade code for different products that have their own "life cycle" and no real relation to each other. They are not related. This is just as important as keeping your upgrade code stable for related products. Think "life cycle" and "family relation" and "co-existence" requirements.
    • That was a large digression, back to the issue at hand: finding upgrade codes.
  3. Even if you don't have the original MSI, it is even possible to locate the cached MSI from the original install in the %SystemRoot%\Installer folder. The MSI files here have a mysterious hex-name, but they are just copies of the original MSI files used to install the different products - cached in a safe place to be available for modify, repair and uninstall operations. Whatever you do, don't mess around in this folder. Never, ever delete anything. You can find the MSI that installed your product by selecting the first MSI file, and checking the Windows Explorer status bar what the product name is for older Windows version. In Windows 10 it seems you can hover over an MSI with the pointer and you get a pop-up with some MSI details. You then just click through the list until you find the right product and open the MSI and find the upgrade code in the Property table.

  4. Some people use the registry to read the upgrade codes: How can I find the upgrade code for an installed application in C#?. In my opinion this is not a good approach, there are better ways - such as just using PowerShell as explained above. There is no need for all this conversion and interpretation of packed GUIDs (which is the GUID format used in the Windows Installer registry database).

That should complete the primary "manual methods" to retrieve an upgrade code quickly. Just some methods for the arsenal that are sometimes good enough. There are probably several more ways that I have forgotten.

Do prefer the programmatic approaches, but if you are in a rush and working without all your tools available some manual options are good. However some of these manual methods require more tools than the PowerShell command line (you need an MSI file viewer which is not always available on the box if you are on a "support mission" to someone's machine). The time has come to use PowerShell (yes, I feel outdated too).

Incidentally, MSI files are essentially stripped down SQL Server databases stored as COM-structured storage files (MS Office file format). Essentially a file system within a file with storage streams of various types.

If you are stuck on a machine without an MSI viewer, you can query cached MSI databases directly from PowerShell:

  • https://gallery.technet.microsoft.com/scriptcenter/Get-MsiDatabaseProperties-09d9c87c
  • http://www.adamtheautomator.com/powershell-windows-installer-msi-properties/