Retract (uninstall and remove) SharePoint solution


Scenario:
You want to retract a solution already deployed to SharePoint. Normally you would use Visual Studio (r-click retract) for this but you don't have Visual Studio installed on the SharePoint server.

PowerShell Script:

$webUrl = "http://site:port"
$wspFileName = "myOldSolution.wsp"

function WaitForJobToFinish([string]$solutionName)
{ 
    $JobName = "*$solutionName*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null) {
        Write-Host 'Timer job not found'
    }
    else {
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"

  $JobFullName = $job.Name
        while ((Get-SPTimerJob $JobFullName) -ne $null) {
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        }
        Write-Host  "done"
    }
}

# Add SharePoint Snapin
Add-PsSnapin Microsoft.SharePoint.PowerShell -erroraction SilentlyContinue
$webApp = Get-SPWebApplication $webUrl

$solution=Get-SPSolution -Identity $wspFileName -ErrorAction:SilentlyContinue
# Check whether the solution exists in the Solutions Store.
if ($solution -ne $null) {
 # Check whether the solution is already deployed.
 if ($solution.Deployed) {
  write-Host "Retracting" $solution.Name -ForegroundColor Yellow
  if ($solution.ContainsWebApplicationResource) {
   Uninstall-SPSolution -identity $solution.Name -allwebapplication -confirm:$false
  }
  else {
   Uninstall-SPSolution -identity $solution.Name -confirm:$false
  }

  WaitForJobToFinish $solution.Name
 }

 # Remove solution from store.
 Write-Host "Removing" $solution.Name -ForegroundColor Yellow          
 Remove-SPSolution –Identity $solution.Name -confirm:$false
}

Leave a Reply