private void LoadUninstallableItems() { var products = ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All).ToArray(); var installations = products .Where(ins => ins.ProductName != null) .Select(ins => new InstalledItem(ins.ProductName, ins.ProductCode, ins.InstallDate, ins.InstallLocation, ins.UrlInfoAbout, ins.ProductVersion, ins.Publisher)) .OrderBy(ins => ins.Product); _logger.Info("Found {0} installed items", installations.Count()); Items = new ObservableCollection <InstalledItem>(installations); FilteredItems = CollectionViewSource.GetDefaultView(Items); FilteredItems.Filter = ItemFilter(); FilteredItems.Refresh(); Cancelling = false; UninstallInProgress = false; UninstallCurrent = 0; UninstallTotal = 0; UninstallProgress = 0; }
/// <summary> /// Installs a product given the provided <paramref name="data"/>. /// </summary> /// <param name="data">An <see cref="InstallProductActionData"/> with information about the package to install.</param> protected override void ExecuteAction(InstallProductActionData data) { if (!string.IsNullOrEmpty(data.TargetDirectory)) { data.CommandLine += string.Format(CultureInfo.InvariantCulture, @" TARGETDIR=""{0}""", data.TargetDirectory); } if (!string.IsNullOrEmpty(data.Path)) { Installer.InstallProduct(data.Path, data.CommandLine); } else if (!string.IsNullOrEmpty(data.ProductCode)) { Installer.ConfigureProduct(data.ProductCode, INSTALLLEVEL_DEFAULT, InstallState.Default, data.CommandLine); } if (this.PassThru) { var product = ProductInstallation.GetProducts(data.ProductCode, null, UserContexts.All).FirstOrDefault(); if (null != product && product.IsInstalled) { this.WriteObject(product.ToPSObject(this.SessionState.Path)); } } }
/// <summary> /// Gets the <see cref="Installation"/> class given the <see cref="Parameters"/>. /// </summary> /// <param name="param">The <see cref="Parameters"/> of the <see cref="Installation"/> to get.</param> /// <returns>An <see cref="Installation"/> given the <see cref="Parameters"/>.</returns> protected Installation GetInstallation(Parameters param) { Installation installation = null; try { if (string.IsNullOrEmpty(param.PatchCode)) { installation = ProductInstallation.GetProducts(param.ProductCode, param.UserSid, param.UserContext).FirstOrDefault(); } else { installation = PatchInstallation.GetPatches(param.PatchCode, param.ProductCode, param.UserSid, param.UserContext, PatchStates.All).FirstOrDefault(); } } catch (InstallerException ex) { var pse = new PSInstallerException(ex); if (null != pse.ErrorRecord) { base.WriteError(pse.ErrorRecord); } } return(installation); }
private static string GetPreviousVersionInstallPath() { var retVal = String.Empty; var products = ProductInstallation.GetProducts("{944871E7-9F8D-47B7-BE04-103E4C8F2254}", null, UserContexts.All); var product = products?.FirstOrDefault(); var location = product?.LocalPackage; if (location != null) { var package = new InstallPackage(location, DatabaseOpenMode.ReadOnly); var componentId = package.Files.FirstOrDefault(kvp => kvp.Value.SourceName == "UO Bulk Order Deeds.exe").Key; if (componentId != null) { var results = package.ExecuteQuery($"SELECT `ComponentId` FROM `Component` WHERE `Component` = 'C_{componentId}'"); var result = results?.Count > 0 ? results[0].ToString() : null; if (result != null) { var componentInstallation = new ComponentInstallation(result); var componentPath = componentInstallation.Path; retVal = Path.GetDirectoryName(componentPath); } } } return(retVal); }
public static OrphanComponent IsOrphanComponent(RegistryKey componentKey) { string[] productCodes = componentKey.GetValueNames(); string compName = Path.GetFileName(componentKey.Name); OrphanComponent orphan = new OrphanComponent(compName); foreach (string p in productCodes) { // Ignore default value if (string.IsNullOrWhiteSpace(p) || p.Equals("@") || p.Equals("00000000000000000000000000000000")) { continue; } Guid productCode = p.MsiObfuscate(); Guid componentGuid = compName.MsiObfuscate(); IEnumerable <ProductInstallation> pis = ProductInstallation.GetProducts(productCode.ToString("B"), null, UserContexts.All); if ((pis == null) || (pis.Count() <= 0)) { string keyPath = componentKey.GetValue(p) as string; Console.WriteLine($"Component '{componentGuid.ToString("B")}' in registry key '{componentKey.Name}' is registered to product '{productCode.ToString("B")} which is not installed with KeyPath='{keyPath}'"); orphan.NonExistingClients.Add(productCode.ToString("B")); } } return(orphan.NonExistingClients.Count > 0 ? orphan : null); }
/// <summary> /// Enumerates products for the given ProductCode and writes them to the pipeline. /// </summary> /// <param name="productCode">The ProductCode of products to enumerate.</param> /// <param name="userSid">The user's SID for products to enumerate.</param> /// <param name="context">The installation context for products to enumerate.</param> /// <param name="patterns">Optional list of <see cref="WildcardPattern"/> to match product names.</param> private void WriteProducts(string productCode, string userSid, UserContexts context, IList <WildcardPattern> patterns = null) { foreach (ProductInstallation product in ProductInstallation.GetProducts(productCode, userSid, context)) { if (0 == patterns.Count() || product.ProductName.Match(patterns)) { this.WriteProduct(product); } } }
/// <summary> /// Uninstalls a package /// </summary> /// <param name="fastPackageReference"></param> /// <param name="requestImpl"> /// An object passed in from the CORE that contains functions that can be used to interact with /// the CORE and HOST /// </param> public void UninstallPackage(string fastPackageReference, RequestImpl requestImpl) { try { // create a strongly-typed request object. using (var request = requestImpl.As <Request>()) { // Nice-to-have put a debug message in that tells what's going on. request.Debug("Calling '{0}::UninstallPackage' '{1}'", ProviderName, fastPackageReference); try { Guid guid; if (!Guid.TryParse(fastPackageReference, out guid)) { request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference); return; } var product = ProductInstallation.GetProducts(fastPackageReference, null, UserContexts.All).FirstOrDefault(); if (product == null) { request.Error(ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference); return; } var productVersion = product.ProductVersion.ToString(); var productName = product.ProductName; var summary = product["Summary"]; Installer.SetInternalUI(InstallUIOptions.UacOnly | InstallUIOptions.Silent); _progressId = request.StartProgress(0, "Uninstalling MSI '{0}'", productName); var handler = CreateProgressHandler(request); Installer.SetExternalUI(handler, InstallLogModes.Progress | InstallLogModes.Info); Installer.InstallProduct(product.LocalPackage, "REMOVE=ALL REBOOT=REALLYSUPPRESS"); Installer.SetInternalUI(InstallUIOptions.Default); Installer.SetExternalUI(handler, InstallLogModes.None); // YieldPackage(product,fastPackageReference, request); if (request.YieldSoftwareIdentity(fastPackageReference, productName, productVersion, "multipartnumeric", summary, "", fastPackageReference, "", "")) { request.YieldSoftwareMetadata(fastPackageReference, "ProductCode", fastPackageReference); } request.Warning("Reboot is required to complete uninstallation."); } catch (Exception e) { e.Dump(); } request.CompleteProgress(_progressId, true); _progressId = 0; } } catch (Exception e) { // We shoudn't throw exceptions from here, it's not-optimal. And if the exception class wasn't properly Serializable, it'd cause other issues. // Really this is just here as a precautionary to behave correctly. // At the very least, we'll write it to the system debug channel, so a developer can find it if they are looking for it. Debug.WriteLine("Unexpected Exception thrown in '{0}::UninstallPackage' -- {1}\\{2}\r\n{3}", ProviderName, e.GetType().Name, e.Message, e.StackTrace); } }
/// <summary> /// Uninstalls a package /// </summary> /// <param name="fastPackageReference"></param> /// <param name="request"> /// An object passed in from the CORE that contains functions that can be used to interact with /// the CORE and HOST /// </param> public void UninstallPackage(string fastPackageReference, Request request) { if (request == null) { throw new ArgumentNullException("request"); } if (string.IsNullOrWhiteSpace(fastPackageReference)) { throw new ArgumentNullException("fastPackageReference"); } // Nice-to-have put a debug message in that tells what's going on. request.Debug("Calling '{0}::UninstallPackage' '{1}'", ProviderName, fastPackageReference); try { Guid guid; if (!Guid.TryParse(fastPackageReference, out guid)) { request.Error(Microsoft.PackageManagement.Internal.ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference); return; } var product = ProductInstallation.GetProducts(fastPackageReference, null, UserContexts.All).FirstOrDefault(); if (product == null) { request.Error(Microsoft.PackageManagement.Internal.ErrorCategory.InvalidArgument, fastPackageReference, Constants.Messages.UnableToResolvePackage, fastPackageReference); return; } var productVersion = product.ProductVersion.ToString(); var productName = product.ProductName; var summary = product["Summary"]; Installer.SetInternalUI(InstallUIOptions.UacOnly | InstallUIOptions.Silent); _progressId = request.StartProgress(0, Resources.Messages.UninstallingMSIPackage, productName); var handler = CreateProgressHandler(request, Resources.Messages.UnInstalling); Installer.SetExternalUI(handler, InstallLogModes.Progress | InstallLogModes.Info); Installer.InstallProduct(product.LocalPackage, "REMOVE=ALL REBOOT=REALLYSUPPRESS"); Installer.SetInternalUI(InstallUIOptions.Default); Installer.SetExternalUI(handler, InstallLogModes.None); // YieldPackage(product,fastPackageReference, request); if (request.YieldSoftwareIdentity(fastPackageReference, productName, productVersion, "multipartnumeric", summary, "", fastPackageReference, "", "") != null) { request.AddMetadata(fastPackageReference, "ProductCode", fastPackageReference); request.AddTagId(fastPackageReference.Trim(new char[] { '{', '}' })); } request.Warning(Resources.Messages.UninstallRequireReboot); } catch (Exception e) { e.Dump(); } request.CompleteProgress(_progressId, true); _progressId = 0; }
/// <summary> /// Return true if it finds the given productcode in system otherwise it returns false /// </summary> /// <param name="prodCode"></param> /// <returns></returns> public static bool IsProductInstalled(string prodCode) { //look in all user's products (both per-machine and per-user) foreach (ProductInstallation product in ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All)) { if (product.ProductCode == prodCode) { return(true); } } return(false); }
/// <summary> /// Installs a patch given the provided <paramref name="data"/>. /// </summary> /// <param name="data">An <see cref="InstallProductActionData"/> with information about the package to install.</param> protected override void ExecuteAction(InstallPatchActionData data) { Installer.ApplyMultiplePatches(data.Patches, data.ProductCode, data.CommandLine); if (this.PassThru) { var product = ProductInstallation.GetProducts(data.ProductCode, null, UserContexts.All).FirstOrDefault(); if (null != product && product.IsInstalled) { this.WriteObject(product.ToPSObject(this.SessionState.Path)); } } }
/// <summary> /// Return a list of ProductInstallation objects. /// For per-machine installs, the list will only contain 1 object. /// For per-user installs, the list will contain an object for each user that installed it. /// </summary> /// <param name="prodCode"></param> /// <returns></returns> public static List <ProductInstallation> GetProducts(string prodCode) { List <ProductInstallation> products = new List <ProductInstallation>(); //look in all user's products (both per-machine and per-user) foreach (ProductInstallation product in ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All)) { if (product.ProductCode == prodCode) { products.Add(product); } } return(products); }
private static void FindProductInstalledFeatures(Session session, string previousProductCode) { var previousProduct = ProductInstallation.GetProducts( previousProductCode, null, UserContexts.Machine).FirstOrDefault(); if (null == previousProduct) { return; } foreach (var feature in previousProduct.Features) { InitializeFeatureProperty(session, feature); } }
private void LoadUninstallableItems() { var installations = ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All) .Where(ins => ins.ProductName != null) .Select(ins => new InstalledItem(ins.ProductName, ins.ProductCode, ins.InstallDate, ins.InstallLocation, ins.UrlInfoAbout, ins.ProductVersion)) .OrderBy(ins => ins.Product); Items = new ObservableCollection <InstalledItem>(installations); Cancelling = false; UninstallInProgress = false; UninstallCurrent = 0; UninstallTotal = 0; UninstallProgress = 0; }
public void Cleanup() { var products = ProductInstallation.GetProducts(ExampleProductCode, null, UserContexts.All); if (products.Any(p => p.IsAdvertised || p.IsInstalled)) { var previous = Installer.SetInternalUI(InstallUIOptions.Silent); try { foreach (var product in products) { Installer.ConfigureProduct(product.ProductCode, 0, InstallState.Absent, null); } } finally { Installer.SetInternalUI(previous); } } }
/// <summary> /// GetInstalledItems lists all items that are installed on this machine. /// </summary> /// <returns></returns> public ICollection <Package> GetAllInstalledItems() { Logger.Log(String.Format(CultureInfo.InvariantCulture, "Getting all installed items", AppName), Logger.MessageLevel.Information, AppName); ICollection <Package> installations = new List <Package>(); try { Logger.Log(String.Format(CultureInfo.InvariantCulture, "Do we already have an object in memory?", AppName), Logger.MessageLevel.Verbose, AppName); if (installedmsis.FirstOrDefault() == null) { Logger.Log(String.Format(CultureInfo.InvariantCulture, "No installpackages object found - creating", AppName), Logger.MessageLevel.Verbose, AppName); installations = ProductInstallation.GetProducts(null, null, UserContexts.All) .Select(ins => new Package( this.GetUpgradeCode(ins.LocalPackage), ins.ProductCode, ins.ProductVersion == null ? "0.0.0" : ins.ProductVersion.ToString(), ApplyFilter(string.IsNullOrEmpty(ins.ProductName) ? "(NOTDEFINED)" : ins.ProductName), null ) ) .OrderBy(ins => ins.ProductName).ToList(); Logger.Log(String.Format(CultureInfo.InvariantCulture, "Packages installed: {0}", installations.Count().ToString(CultureInfo.InvariantCulture))); } else { Logger.Log("installedpackages is populated."); installations = (List <Package>)installedmsis; } } catch (Exception ex) { Logger.Log(ex.Message, Logger.MessageLevel.Error, AppName); } installedmsis = installations; return(installations); }
/// <summary> /// Repairs a product given the provided <paramref name="data"/>. /// </summary> /// <param name="data">An <see cref="RepairProductActionData"/> with information about the package to install.</param> protected override void ExecuteAction(RepairProductActionData data) { string mode = this.converter.ConvertToString(data.ReinstallMode); data.CommandLine += " REINSTALL=ALL REINSTALLMODE=" + mode; if (!string.IsNullOrEmpty(data.Path)) { Installer.InstallProduct(data.Path, data.CommandLine); } else if (!string.IsNullOrEmpty(data.ProductCode)) { Installer.ConfigureProduct(data.ProductCode, INSTALLLEVEL_DEFAULT, InstallState.Default, data.CommandLine); } if (this.PassThru) { var product = ProductInstallation.GetProducts(data.ProductCode, null, UserContexts.All).FirstOrDefault(); if (null != product && product.IsInstalled) { this.WriteObject(product.ToPSObject(this.SessionState.Path)); } } }
/// <summary> /// Sequences and returns the ordered list of <see cref="PatchSequence"/> objects for all applicable patches. /// </summary> protected override void EndProcessing() { IEnumerable <PatchSequence> patches = null; if (this.IsProductCode) { // If not specified, check all contexts for the ProductCode. if (UserContexts.None == this.UserContext) { this.UserContext = UserContexts.All; } foreach (string productCode in this.ProductCode) { var product = ProductInstallation.GetProducts(productCode, this.UserSid, this.UserContext).FirstOrDefault(); if (null != product) { patches = this.sequencer.GetApplicablePatches(productCode, product.UserSid, product.Context); this.WritePatchSequence(patches); } } } else { ProviderInfo provider; foreach (string packagePath in this.PackagePath) { var paths = this.SessionState.Path.GetResolvedProviderPathFromPSPath(packagePath, out provider); foreach (string path in paths) { patches = this.sequencer.GetApplicablePatches(path); this.WritePatchSequence(patches); } } } }
static void Main(string[] args) { try { var command = Args.Configuration.Configure <CommandObject>().CreateAndBind(args); // Get the installed MSI Products IEnumerable <ProductInstallation> installations = ProductInstallation.GetProducts(null, "s-1-1-0", UserContexts.All); if (!command.ListAll && !command.Filter && !command.Uninstall) { printCommands(); } if (command.ListAll) { // Loop through the installed MSI Products and output information foreach (ProductInstallation installation in installations) { Console.WriteLine("Name: " + installation.ProductName); Console.WriteLine("Product Code: " + installation.ProductCode); Console.WriteLine(); } } else if (command.Filter) { IEnumerable <string> productNameSubstrings = GetListOfProductNameSubstringsToUninstallFromConfig(); foreach (ProductInstallation installation in installations) { if (string.IsNullOrEmpty(installation.ProductName)) { continue; } if (productNameSubstrings.Any(installation.ProductName.Contains)) { Console.WriteLine("Name: " + installation.ProductName); Console.WriteLine("Product Code: " + installation.ProductCode); Console.WriteLine(); } } } else if (command.Uninstall) { IEnumerable <string> productNameSubstrings = GetListOfProductNameSubstringsToUninstallFromConfig(); List <ProductInstallation> productsToUninstall = new List <ProductInstallation>(); foreach (ProductInstallation installation in installations) { if (string.IsNullOrEmpty(installation.ProductName)) { continue; } if (productNameSubstrings.Any(installation.ProductName.Contains)) { productsToUninstall.Add(installation); Console.WriteLine("Name: " + installation.ProductName); Console.WriteLine("Product Code: " + installation.ProductCode); Console.WriteLine(); } } foreach (ProductInstallation productInstallation in productsToUninstall) { Console.WriteLine("Uninstalling " + productInstallation.ProductName); Console.WriteLine(); Uninstall(productInstallation.ProductCode); } } } catch (Exception) { printCommands(); } }
public static void GetAllProducts() { var allPrds = ProductInstallation.GetProducts(null, null, UserContexts.All); int i = 0; if (isFilterOn && filterString != "") { root.Text = System.Environment.MachineName + " filtered by \"" + filterString + "\""; } else { root.Text = System.Environment.MachineName; } foreach (ProductInstallation p in allPrds) { // if (string.IsNullOrEmpty(p.ProductName)) continue; if (isFilterOn && filterString != "") { if (string.IsNullOrEmpty(p.ProductName)) { continue; } else if (!p.ProductName.ToLower().Contains(filterString.ToLower())) { continue; } } try { UpdateProgress("Processing (" + i + ") " + p.ProductName); i++; //if (i > 40) break; TreeNode node = new TreeNode(p.ProductName); node.Name = p.ProductName; root.Nodes.Add(node); TreeNode nodeProp = new TreeNode("Properties"); node.Nodes.Add(nodeProp); try { AddProductProperty(nodeProp, p); } catch (Exception ex) { TreeNode error = new TreeNode(ex.Message); nodeProp.Nodes.Add(error); Logger.LogError(p.ProductName + ":" + ex.Message); } List <PatchInstallation> patches = PatchInstallation.GetPatches(null, p.ProductCode, null, UserContexts.All, PatchStates.All).ToList(); if (patches.Count > 0) { TreeNode pa = new TreeNode("Patches"); node.Nodes.Add(pa); foreach (PatchInstallation pch in patches) { TreeNode nd = new TreeNode(pch.DisplayName); nd.Name = pch.DisplayName; pa.Nodes.Add(nd); try { AddPatchProperty(nd, pch); } catch (Exception ex) { TreeNode error = new TreeNode(ex.Message); nd.Nodes.Add(error); Logger.LogError(pch.DisplayName + ":" + ex.Message); } } } if (p.Features != null) { List <FeatureInstallation> lst = p.Features.ToList(); if (lst.Count > 0) { TreeNode pa = new TreeNode("Features"); node.Nodes.Add(pa); foreach (FeatureInstallation fi in lst) { string txt = "FeatureName : " + fi.FeatureName + "; State : " + fi.State.ToString(); TreeNode nd = new TreeNode(txt); nd.Name = nd.Text; pa.Nodes.Add(nd); nd.ImageIndex = 1; nd.SelectedImageIndex = 1; } } } } catch (Exception ex) { Logger.LogError("GetAllProducts:ProductCode:" + p.ProductCode + "\n" + ex.Message); } } }
///<inheritdoc/> public IEnumerable <IProductInstallation> GetProducts(string productCode, string userSid, UserContexts context) { return(ProductInstallation.GetProducts(productCode, userSid, context).Select(x => new ProductInstallationWrap(x) as IProductInstallation)); }
private static ProductInstallation GetInstalledProduct(string productCode) { return(!string.IsNullOrEmpty(productCode) ? ProductInstallation.GetProducts(productCode, null, UserContexts.Machine).FirstOrDefault() : null); }