Quickly Remove Software using PowerShell (Part 2)

Removing Software


In the last post we looked at listing all of your applications without using the dreaded WMI/CIM cmdlets (to clarify, I love these cmdlets but they can cause problems with reconfiguring software whilst scanning - it's a feature!).


So for reference, we got to listing software:-

Get-childitem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-itemProperty | Select DisplayName,DisplayVersion

So what can we do with it now? lets take a look at what we have to play with. I am going to use the where-object (? alias) to filter the list to a small application. In this case 7zip.

  gci HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-ItemProperty | ? displayname -like "7-zip*"

(notice that the where cmdlet can take parameters two ways. The traditional programmer's way which would be: ? {$_.displayname -like "7-zip"} Or the natural language way by: ? displayname -like "7-zip" ).

 





Now we can see the properties of which the uninstall string is interesting.


So we can now be cute and tell PowerShell to run that command.

gci HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-ItemProperty | ? Displayname -like "Powershell*preview*" | Select -exp uninstall* | iex
This will now pull the install string from the object and pipe that to invoke-expression (iex). if there is a quite installer then you could manipulate this string and add "/q" for example.

Some uninstall strings will be awkward, especially MSI installed ones :



See the { and } in the install string? that's going to cause problems when passing to invoke expression. Not to worry we can just escape those characters.


(gci HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\ | Get-ItemProperty | ? Displayname -like "Powershell*" | Select -exp uninstall*).replace('{','`{').replace('}','`}')  | iex

What we are doing here is grabbing the uninstall string then running the inbuilt replace command to escape the characters by replacing "{" with "`{"  (note that it is a backtick) and doing the same for the closing bracket.


We then pipe that to invoke-expression and boom, we are now running the uninstall process.


Where this gets really powerful is again when we run this command against multiple other machines with 

"invoke-command -computers $computerlist -scriptblock { get-childitem ..."

Running this against multiple computers will save you loads of time RDP'ing into remote computers just remember you will need to use the /q or quiet string to ensure that you don't get a pop up asking you to confirm you want to uninstall the application as this will be run in a remote PS session.

Have fun, feel free to let me know if you want more details on this very slick one-liner.

Comments