Uninstall applications on multiple machines

Today I’ve got for you quite easy, but very usefull script for uninstall applications on multiple machines.

Below script is using WMI objects – Win32_Product class to check if application exist on some servers.
If it exist Uninstall method is used which uninstall applications.

As an input for script CSV file should be provided.
It should contains two headers: ServerName and ApplicationName.

Script:

function Add-ArrayRow{
   param
   (
   [Parameter(Position=0, Mandatory = $true, HelpMessage="Server name", ValueFromPipeline = $true)] 
   $ServerName,
   [Parameter(Position=1, Mandatory = $true, HelpMessage="Application", ValueFromPipeline = $true)]
   $Application
   )
 
   $Object = New-Object PSCustomObject
   $Object | Add-Member -MemberType NoteProperty -Name "ServerName" -Value $ServerName
   $Object | Add-Member -MemberType NoteProperty -Name "Application" -Value $Application
   return $Object
}

$CSV = Import-Csv -Path <your_path_to_CSV>
$AppNotFound = @()
$AppRemoved = @()
$AppNotRemoved = @()

foreach($item in $CSV)
{

    $ApplicationName = $item.applicationName
    $ComputerName = $item.servername
    $Row = Add-ArrayRow -ServerName $ComputerName -Application $ApplicationName   
    

    $application = Get-WmiObject -Class Win32_Product -ComputerName $ComputerName -Filter "Name='$ApplicationName'"
    If($application -ne $null)
    {
        $Result = $application.Uninstall()
        If ($Result.ReturnValue -eq 0)
        {   
            Write-Verbose -Verbose "[$(Get-Date)] - $ComputerName uninstallation of $($application.name) successful!"
            $AppRemoved += $Row
        }
        Else
        {   
            Write-Error -Verbose "[$(Get-Date)] - $ComputerName uninstallation of $($application.name) failed!  Error code: $($Result.ReturnValue)"
            $AppNotRemoved += $Row
        }
    }
    Else
    {
        Write-Verbose -Verbose "[$(Get-Date)] - $ComputerName does not have $ApplicationName application installed!"
        $AppNotFound += $Row
    }

}

Result:

I know it’s not best solution as performance of remote connection to WMI is very slow, but it works!
If you have solution with better performance to uninstall applications remotely, please leave a comment.

I hope it will be usefull for some of you 🙂
Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.