Remove non-windows MSP packages with powershell - powershell

I'm trying to remove a Non-Microsoft MSP from a server that is running Win2k3 or Win2k8. The Update does show up in the Add/Remove programs when selecting "View Installed Updates". However I can't seem to find a way to get the MSP GUID.
I planned on using
msiexec /i {GUID-OF-PRODUCT} MSIPATCHREMOVE={GUID_OF_PATCH} /qb
that was found in this article: how to remove the Patch from console
However, I don't have a way to get the Patch GUID from the command line. Has anyone else been able to do something like this? There's plenty of ways to do this for Microsoft Patches, but since this is non-Microsoft, I'm hoping it's still possible.
Thanks,
Greg

You can use the Windows Installer com object to enumerate the patches.
Check out this article. It doesn't do exactly what you need, but it provides the comObject.types.ps1xml file you will need:
http://www.snowland.se/2010/02/21/read-msi-information-with-powershell/
Then you can do this to get the patch:
$installer_obj = New-Object -com WindowsInstaller.Installer;
$patches = $installer_obj.InvokeParamProperty("PatchesEx", "Product-Code-GUID", "s-1-1-0", 7, 15);
Product-Code-GUID is the GUID for the product you are interested in. I prefer to enumerate a list of products as well, and get the GUID programmatically based on the human readable name (i.e. the one that is displayed in Add/Remove Programs).
$installer_obj = New-Object -com WindowsInstaller.Installer;
$all_products = $installer_obj.GetProperty("Products");
foreach($product_code in $all_products) {
$product_name = $installer_obj.InvokeParamProperty("ProductInfo", $product_code, "ProductName")
if($product_name -eq "MySQL Server 5.1") {
$interesting_product_code = $product_code;
}
}
$patches = $installer_obj.InvokeParamProperty("PatchesEx", $interesting_product_code, "s-1-1-0", 7, 15);
Either route you take, now you just need to loop through the $patches and call msiexec from the command line with the proper arguments (if you are opting to use a literal string for the $interesting_product_code, just replace the variable and concatenation with the literal string GUID.):
foreach($patch in $patches) {
$patch_code = $patch.GetProperty("PatchCode");
$argument_list = "/I" + $interesting_product_code + " MSIPATCHREMOVE=$patch_code /qb /norestart";
Start-Process -FilePath "msiexec.exe" -ArgumentList $argument_list -Wait;
}
Here is a reference to the Windows Installer com object. You can do some other fun stuff with it too:
http://msdn.microsoft.com/en-us/library/windows/desktop/aa369432%28v=vs.85%29.aspx
Hope that helps,
Aaron

Related

How do I add a powershell script to be run post setup during a windows 10 unattended install?

I may be going about this the wrong/more difficult way. I am open to suggestions.
I am running NTLite v2.3.8.8920 [HOME] ((c) NTlitesoft d.o.o) to create unattended Windows 10 discs. After years of doing unattended discs and realizing the ever expanding size of the disc, (Latest disc was 32.73GB!), I found WinGet, the absolutely amazing repository, and have even gone as far as to create my own installer!
The issue for today is: how do I access WinGet during an unattended installation? I have compiled a list of applications that I use frequently; most that I have been hard coding to the disc and thus this incredible size; and I would love to be able to run this script post-setup and save the time and space. Here is my code:
#The first batch here is a function I created for notification purposes. Not sure how to do timed popups in Powershell yet.
#Get Words
function GW($myinput){
$WS = New-Object -ComObject "Wscript.Shell"
$ws.popup($myinput,3,'TK Installer',64)|SET-CLIPBOARD}
SET-CLIPBOARD to offload the popup response code. Need to find a better output or a way to prevent printing this response.
function install-myapps(){
Clear-Host
#Variable to hold the application list
$myapps = (
'Microsoft.PowerShell',
'Microsoft-Windows.Terminal',
'Microsoft.DotNet.SDK.3_1',
'Microsoft.DotNet.SDK.5',
'Microsoft.DotNet.SDK.6',
'Microsoft.MSIXCore',
'Microsoft.msmpisdk',
'Microsoft.ADKPEAddon',
'Microsoft.WebDeploy',
'9N5LW3JBCXKF',
'Nlitesoft.NTLite',
'Libretro.RetroArch',
'Notepad++.Notepad++',
'CodecGuide.K-LiteCodecPack.Full',
'Foxit.FoxitReader',
'7zip.7zip',
'OBSProject.OBSStudio',
'XnSoft.XnConvert',
'XnView.Classic',
'XnSoft.XnViewMP',
'corel.winzip',
'XP8K0J757HHRDW')
#Parser
ForEach-Object($aa in $myapps.Split(',')){
#Notification
GW "Installing $aa`nPlease wait..."
#Installer
WinGet install $aa --silent --accept-package-agreements --accept-source-agreements --force}
}
This code works perfectly in both command line and exe format; the latter using PS2EXE or IExpress. I just cannot figure out how to instantiate it post-setup from the unattended Win1021H2 side. Any help or insight would be greatly appreciated!
I was unable to figure out the process for this so I worked it around differently.
Below is how I fixed this situation:
# The first section opens and names function and
# declares variable $Hopeful applied to the full URI for the application we are installing
# !Considering using get-input but for now we will just use a replaceable variable!
# The second section begins the downloading and saving process
# Begins by separating the application from the URI assuming the format is as www.domain.com/application.exe
# Note now that the variable $JustApp will pull the just the last portion of the URI which is the application name
# Also, we'll make sure that what we're trying to do is possible by checking the extension of the last object
# Because wget needs 2 things; the URI and a place for the download to go; I am creating a directory to put these
# downloads in. Thus, $MyDir\$JustApp is now the default file point.
cls
Clear-Host
$MyDir = "d:\TKDI\"
# Create directory
if($mydir|Test-Path){
"My Directory Already Exists!"
}else{
md $MyDir -Force
}
# Section 1
Function TKDI($Hopeful,$MyArgs){
$_|select
# Section 2
$JustApp = $hopeful -split('/')|select -last 1
if($justapp -match "exe")
{
switch($MyArgs)
{
inno{$x ='/sp- /silent /forcecloseapplications /restartapplications /norestart'}
S{$x ='/S'}
silent{$x ='/silent'}
quiet{$x ='/quiet'}
passive{$x ='-passive'}
default{$x =$myargs}
un{$x ='-uninstall'}
$null{$x='/?'}
}
cls
echo "Processing $justapp"
if(Test-Path $mydir$justapp -PathType Leaf){echo 'File Downloaded Already!'}else{wget -Uri $hopeful -OutFile $MyDir$justapp}
$noteit = 'Installing $justapp in 5 seconds...'
$x=6;while($x-- -ge 1){cls;Write-host $x;sleep 1}
start -verb runas -wait -FilePath $mydir$justapp -ArgumentList $x
}elseif($justapp -match "msi")
{
cls
echo "You're file will be downloaded and installed!"
wget -Uri $hopeful -OutFile $MyDir$justapp
start -wait -Verb runas msiexec.exe -ArgumentList "-i $mydir$justapp /passive /norestart"
}else{
echo "This URI does not result in an application!"
}
}
tkdi www.example.com/index.exe inno #Installs beautifully```

Get installed software product context using powershell

I can easily get all installed software products on a machine using
Get-WmiObject -Class Win32_Product
Now I'd like to also fetch the Product Context. How can I access this information for every installed product using PowerShell.
In VB I did that by using the WindowsInstaller COM-Object and then querying the information. In essence this:
Set Com = CreateObject('WindowsInstaller.Installer')
Set Products = Com.ProductsEx(vbNullString,"S-1-1-0",7)
For Each P in Products
context = P.Context
Which I dont not manage to replicate in PowerShell
I realize this question is a bit stale, but I disagree with what seems to be the prevailing notion that working with Windows Installer in PowerShell is somehow a "pain" and more complicated than working with it in VBScript (this post is just one of many).
I have found that VBScript Windows Installer code translates quite literally to PowerShell, which means there are numerous examples of VBScript Windows Installer scripts that can be adapted to PowerShell and used to learn how to work with Windows Installer in PowerShell.
For this specific question of install context, the PowerShell code is quite similar to the VB code the OP gave.
# code must be run with admin rights to use "S-1-1-0" SID
enum InstallContext {
FirstVisible = 0 # product visible to the current user
None = 0 # Invalid context for a product
UserManaged = 1 # user managed install context
UserUnmanaged = 2 # user non-managed context
Machine = 4 # per-machine context
All = 7 # All contexts. OR of all valid values
AllUserManaged = 8 # all user-managed contexts
}
$Installer = New-Object -ComObject WindowsInstaller.Installer
foreach ($P in $Installer.ProductsEx("", "S-1-1-0", 7)) {
[InstallContext]$P.Context()
}
NOTE: I used Enums (about Enum - PowerShell | Microsoft Docs) with PowerShell here since tagMSIINSTALLCONTEXT is an enum in the msi.h file.
It's a pain to use that com object in powershell. I would use vbscript instead and save the text output to a powershell variable, or find an msi powershell module. That com object doesn't have a "type library" or support "IDispatch". The Windows Powershell in Action appendix for 2nd edition goes into it, but even there it's not pretty. That vbscript code has errors.

Install software from a list using Powershell

I am building a script to automate computer build and configuration: The idea is that from WDS it comes as clean as possible, automatically runs this script which will check the serial number, query our Workday database of assets and configure the OS according to what the user assigned to that system needs.
Right now I am focusing on 3 big groups: Laptop, Desktop, and Lab. All 3 will have some SW that will be the same and some that will be specific for each. My issue is with msiexec: Initially, I hard-coded all the installations for each group. but this means that I will have to change the script each time something is updated (say a new app is rolled out as default). which is not ideal.
function Install-Desktop {
#Write-Output "Here will be the install Desktop computer script"
$IPATH="<Path To root sw folder>"
#Software List
<# SOFTWARE LIST #>
$office="$IPATH\script\o365"
$webex="$IPATH\script\webex"
$chrome="$IPATH\script\chrome"
#install Ofice:
Invoke-Expression "$office\setup.exe /configure $office\O365.xml"
$params = '/i', "$webex\webexapp.msi",'/qb!','/norestart'
Start-Process msiexec -ArgumentList "$params" -Wait -PassThru
$params = '/i', "$chrome\GoogleChromeStandaloneEnterprise64.msi",'/qb!','/norestart'
Start-Process msiexec -ArgumentList $params -Wait -PassThru
}
This piece of code works well.
Now my idea was to import from a list the software to be installed (it is easier to maintain a list than to modify the script every time). something like:
function install-software {
param (
[String]$Type
)
$IPATH=<ROOT SW Folder>
$SoftWares=Import-Csv -Path "$IPath\script\$Type`.csv" #there will be a Laptop.csv in that path
foreach ($Software in $SoftWares) {
#detect if it is msiexect or other:
# (this has to do with how the csv is built, the first parameter is '/i' if it is an msi installer)
if ($Software.param1 -eq "'/i'") {
Start-Process msiexec -ArgumentList $Software -Wait -PassThru
}
else {
$Params=[string]::Join(" ",$Software.param1,$Software.param2,$Software.param3,$Software.param4)
Invoke-Expression "$Params"
}
}
}
This only works on the else part. However on the msiexec side of the if, the MSI opens as without arguments. I tried a lot of ways to pass the args, none worked. I am not a PowerShell guru in any way, so there is probably something that I am missing to see here.
Well, it looks like you have to pass the full path, it doesn't even let you use mounted net drive: so the answer was on the csv. instead of S:\<path to installer> it had to be \<Full path to installer> and i had to get rid of all the quotes and double quotes as well.

Powershell: Uninstall application by UpgradeCode

When I upgrade / downgrade my application via a Powershell script, I want to first force the uninstallation of the currently installed version before running the new installer.
How can I do that with Powershell, using the UpgradeCode of the application?
Doing it by application name would be less robust.
Since you mention upgrade code, it must mean that you are talking about an MSI file (Windows Installer). As stated by others such an uninstall is normally performed auto-magically by a properly authored MSI package - it is referred to as a major upgrade - which is essentially an uninstall of the existing version of a product and then the install of the newest version.
The Upgrade Table of the MSI being installed will specify what existing packages on the box will be uninstalled before the new version is installed. In theory you can uninstall any number of existing installations. You can even uninstall a competitive product if you are mad as a hatter. Frankly, and astonishingly, I have never tried to uninstall multiple products during one major upgrade - it is rarely called for. In most cases you uninstall a single, existing product and then install your latest version.
You can modify the Upgrade table using a transform to change how the major upgrade behaves - in other words to make it start or stop uninstalling a specific pre-existing installation.
You can also enumerate all related products that share the same upgrade code by calling this MSI API function (COM - VBScript used as sample):
Set installer = CreateObject("WindowsInstaller.Installer")
' Enumerate all products related to "Microsoft Visual C++ 2008 Redistributable - x86 9.0.30729.4148"
' {AA783A14-A7A3-3D33-95F0-9A351D530011} is the upgrade code
Set upgrades = installer.RelatedProducts("{AA783A14-A7A3-3D33-95F0-9A351D530011}")
For Each u In upgrades
MsgBox u, vbOKOnly, "Product Code: "
Next
Then you can uninstall the products by passing the product code(s) to the msiexec.exe command line (see below for how to do this via MSI API COM automation instead):
msiexec.exe /x {11111111-1111-1111-1111-11111111111X} /L*V "C:\msilog.log" REBOOT=ReallySuppress
Quick Parameter Explanation (since I recommend this option):
/X = run uninstall sequence
/QN = run completely silently
/L*V "C:\msilog.log"= verbose logging at path specified
{11111111-1111-1111-1111-11111111111X} = product guid of app to uninstall
REBOOT=ReallySuppress = prevent reboot without warning (badly authored MSI packages)
If you don't want to uninstall via msiexec.exe, then you can find a myriad of ways to invoke an MSI uninstall here:
Uninstalling an MSI file from the command line without using msiexec.
And you can find the product code of an installed MSI in several different ways: How can I find the product GUID of an installed MSI setup?
UPDATE: I guess I forgot the obvious, you can uninstall directly via MSI API automation. In the script below we get all products sharing the same upgrade code and then uninstall them in sequence.
Note that when run silently you should run with admin rights since the UAC may be suppressed and then the uninstall will usually fail (permission denied). Because of this the below script runs the uninstall interactively - allowing UAC prompting and elevation.
And if it isn't obvious: running this script will uninstall Orca! I use this product as a sample because it is quick to install again (hints on finding the installer quick if you need to towards bottom here - search for "orca"):
BIG DISCLAIMER:
The COM method installer.ConfigureProduct does not accept any arguments that allow us to pass in REBOOT=ReallySuppress. This means that a (very) badly authored package which triggers the ScheduleReboot action (or uses some more obscure magic to cause a reboot) - may reboot the system without warning if you run the below script with admin rights and in silent mode.
There is a newer call ConfigureProductEx which is available as a Win32 function, but it is not exposed via the COM automation interface. If you platform invoke you can use that call - there is a C++ example in section 14 here: Uninstalling an MSI file from the command line without using msiexec. Or you can use the DTF feature from the WiX toolkit (see section 6 in the same link as the C++ example).
UPDATE July 2018:
Set installer = CreateObject("WindowsInstaller.Installer")
installer.InstallProduct "product.msi", "REMOVE=ALL REBOOT=ReallySuppress"
Set installer = Nothing
Perhaps the above snippet is the best uninstall approach? This should suppress any reboots. I don't have the time or the setup to test it right now (on a Linux box), but I wanted to add it before I forget.
Original uninstall script:
Const msiUILevelNone = 2
Const msiInstallStateAbsent = 2
Set installer = CreateObject("WindowsInstaller.Installer")
'installer.UILevel = msiUILevelNone ' Disabled to prevent silent uninstall. Now the UAC prompt will show
' Uninstall Orca, replace upgrade code with yours
Set products = installer.RelatedProducts("{CFF4D510-79B2-1CCD-0061-5741A0565A76}")
For Each product In products
' MsgBox "Product Code: " & product ' Show the product code found, if you want
' The following call when run silently with admin rights may reboot the system without warning!
' This is due to badly authored MSI packages - most packages will not trigger this problem.
installer.ConfigureProduct product, 0, msiInstallStateAbsent ' Uninstall product
' See text above for info on the newer ConfigureProductEx method.
Next
Set installer = Nothing
MsgBox "Finished" ' Just so we know the script ran if nothing found to uninstall
Some Links:
Is there an alternative to GUID when using msiexec to uninstall an application? (uninstall by product name)
How can I uninstall an application using PowerShell?
How can I use powershell to run through an installer?
WIX (remove all previous versions)
Wix upgrade goes into maintenance mode and never does upgrade (various ways to uninstall, by product code, by upgrade code, etc...)
Since the question specifically mentions powershell I'll just put this here too. There are other PS solutions around using WMI and/or Get-Package. This solution is based off of https://outnull.wordpress.com/2016/11/02/uninstalling-application-based-on-upgradecode/ but accepts various forms of upgrade code syntax, and it tries to avoid string manipulation when converting to/from the package/upgrade Guid and the registry representation.
$upgradecode = "{CFF4D510-79B2-1CCD-0061-5741A0565A76}"
$installer = Join-Path -Path $env:SystemRoot -ChildPath "system32\msiexec.exe" -Resolve
function Reverse-Nibbles {
param ( [byte[]] $bytes )
# reverse nibbles of each byte
for($i = 0; $i -lt $bytes.Length; $i++ )
{
$bytes[$i] = (($bytes[$i] -band 0x0F0F) -shl 4) -bor (($bytes[$i] -band 0xF0F0) -shr 4)
}
Write-Output -NoEnumerate $bytes
}
function GuidToRegString {
param ( [guid] $guid )
$bigendian = (Reverse-Nibbles $guid.ToByteArray())
return [System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary]::new($bigendian).ToString()
}
function RegStringToGuid {
param ( [string] $guid )
$littleendian = (Reverse-Nibbles ([System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary]::Parse($guid).Value))
return [guid]::new($littleendian)
}
$upcode = GuidToRegString ([guid]::Parse($upgradecode))
if (Test-Path -Path "HKLM:\Software\Classes\Installer\UpgradeCodes\$upcode") {
$products = RegStringToGuid (Get-Item -Path "HKLM:\Software\Classes\Installer\UpgradeCodes\$upcode").Property
foreach ($prod in $products) {
$pguid = [guid]::new($prod)
$p = $pguid.ToString("B")
if ((Test-Path -Path "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\$p") -or
(Test-Path -Path "HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\$p"))
{
$logfile = Join-Path -Path $PSScriptRoot -ChildPath uninstall-$($pguid.ToString("D")).log
$args = #( "/x", $p, "/l*v", """$logfile""", "/q", "COMPLETE_UNINSTALL=1", "REBOOT=REALLYSUPPRESS" )
Write-Host "Uninstalling $p"
$uninst = Start-Process -FilePath """$installer""" -ArgumentList $args -PassThru -Wait
Write-Host $uninst.ExitCode
}
}
}

Display progress of exe installation from powershell?

I'm installing a file through powershell silently, but would like to give feedback on the progress of the installation. I can't seem to find this information anywhere. This is the code I have for running the exe:
$exe = "wls1033_oepe111150_win32.exe"
$xmlLocation = Resolve-Path "silent_install.xml"
$xmlLocation = "-silent_xml=" + $xmlLocation
$installLogLoc = Resolve-Path "wls_install.log"
$installLogLoc = "-log=" + $installLogLoc
$AllArgs = #('-mode=silent', $xmlLocation, $installLogLoc)
$filePath = Resolve-Path $exe
$p = New-Object System.Diagnostics.Process
$p.StartInfo.Filename = $filePath
$p.StartInfo.Arguments = $AllArgs
$p.Start();
$p.WaitForExit();
Is there even a way to do this? I do get a progress meter for the extraction process in an alternate command window that installs the exe, but other than that it sits for there about 10 minutes with no sort of indication.
Edit: So seeing as this isn't possible, is there a way to do an asynchronous pipeline call while running the exe?
Thanks
Please correct me if I'm wrong, but I'm 99% sure that this is NOT possible. Your exe file is seperate process and not a PowerShell script. It will not be able to pass status messages to your PowerShell sessions. The only possibility would be to detect the setups log-file, tail it and update a progressbar in PowerShell based on keywords from the log. This is however a big task and something you need to customize for each setup file.
I would try to look into your exe file and see if it has a "basic ui" (or a similar type) mode that you can use instead of the silent option. A last alternative would be to repackage the setup with such an option(making installation automated with only progressbar). This solution would still only show the progressbar in a separate window and not in PowerShell itself.