Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crsuarez/89dd2ed05ef0a39fb0bad755c0492140 to your computer and use it in GitHub Desktop.
Save crsuarez/89dd2ed05ef0a39fb0bad755c0492140 to your computer and use it in GitHub Desktop.
Getting the Product ID / GUID from MSI file
# Vars
$msiPath = 'C:\Users\arush\Downloads\sqlncli.msi'
# Definition
$sig = @'
[DllImport("msi.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
private static extern UInt32 MsiOpenPackageW(string szPackagePath, out IntPtr hProduct);
[DllImport("msi.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
private static extern uint MsiCloseHandle(IntPtr hAny);
[DllImport("msi.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true, ExactSpelling = true)]
private static extern uint MsiGetPropertyW(IntPtr hAny, string name, StringBuilder buffer, ref int bufferLength);
private static string GetPackageProperty(string msi, string property)
{
IntPtr MsiHandle = IntPtr.Zero;
try
{
var res = MsiOpenPackageW(msi, out MsiHandle);
if (res != 0)
{
return null;
}
int length = 256;
var buffer = new StringBuilder(length);
res = MsiGetPropertyW(MsiHandle, property, buffer, ref length);
return buffer.ToString();
}
finally
{
if (MsiHandle != IntPtr.Zero)
{
MsiCloseHandle(MsiHandle);
}
}
}
public static string GetProductCode(string msi)
{
return GetPackageProperty(msi, "ProductCode");
}
public static string GetProductName(string msi)
{
return GetPackageProperty(msi, "ProductName");
}
'@
$msiTools = Add-Type -PassThru -Namespace 'Microsoft.Windows.DesiredStateConfiguration.PackageResource' -Name 'MsiTools' -Using 'System.Text' -MemberDefinition $sig
# Get the MSI Product Name
$msiProductName = $msiTools::GetProductName($msiPath)
Write-Host "[$msiProductName]" -ForegroundColor 'Yellow'
### Example Result: [Microsoft SQL Server 2012 Native Client ]
# Get the MSI Product ID / GUID
$msiProductGuid = $msiTools::GetProductCode($msiPath)
Write-Host "$msiProductGuid" -ForegroundColor 'Yellow'
### Example Result: {49D665A2-4C2A-476E-9AB8-FCC425F526FC}
$x86Path = "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*"
$installedItemsX86 = Get-ItemProperty -Path $x86Path | Select-Object -Property PSChildName, DisplayName, DisplayVersion
$x64Path = "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*"
$installedItemsX64 = Get-ItemProperty -Path $x64Path | Select-Object -Property PSChildName, DisplayName, DisplayVersion
$installedItems = $installedItemsX86 + $installedItemsX64
$installedItems | Where-Object -FilterScript { $null -ne $_.DisplayName } | Sort-Object -Property DisplayName | Out-GridView
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment