PowerShell: Uninstalling an Application

$appname='Google Chrome'

function uninstallApp($appName){
  $alternativeMethod=$false
  try{
    $app = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq $appName}
    $app.Uninstall()
  }catch{
    write-warning $_
    $alternativeMethod=$true
  }
  if($alternativeMethod){
    try{
      $uninstallStrings = (Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall|
      Get-ItemProperty|Where-Object {$_.DisplayName -match $appName}).UninstallString
      ForEach ($uninstallString in $uninstallStrings) {
              $uninstallCommand = $uninstallString.Replace('{',' ').Replace('}',' ')+'ACCEPT=YES /qr+'
              write-host "Attempting alternative method of invoking: $uninstallCommand"
              Invoke-Expression $uninstallCommand
      }
      return $true
    }catch{
      return $false
    }
  }else{
    return $true
  }
}

uninstallApp $appname

Leave a Reply

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