Thursday, October 18, 2012

Powershell Script to Automatically Deploy Sharepoint WSP Packages

Recently I wanted to automate the retraction, removal and deployment of WSP packages in a folder. So I wrote this powershell script.

NOTE: There is a bug in the script that returns a false positive. The property $solution.Deployed returns true even though the object is not finished deploying or is locked! I will update this code or if you do then please send your updated code and I will update my post.

$packages = (dir *.wsp | Select-Object name)
$currentDir = (Get-Location).Path
Add-PSSnapin Microsoft.Sharepoint.PowerShell -ErrorAction "SilentlyContinue"
Write-Host "Started package installation"
foreach ($i in $packages)
{
    Write-Host "Retracting: " + $i
    $solution = (Get-SPSolution | where-object {$_.Name -eq $i.Name})
    Write-Host $solution.Name
    if ($solution -ne $null)
    {
  Write-Host "Solution Found..."
    if ($solution.Deployed -eq $true)
    {
  Write-Host "Uninstalling..."
    Uninstall-SPSolution -Identity $i.Name -AllWebApplications -Confirm:$false 
   
    do
 {
  Write-Host "Waiting for retract to complete..."
    $solution = (Get-SPSolution | where-object {$_.Name -eq $i.Name})
 Start-Sleep -s 5
Write-Host $solution.Deployed
 }
 until ( $solution.Deployed -eq $false)
     }
    Write-Host "Removing Solution..."
    Remove-SPSolution -Identity $i.Name -Force -Confirm:$false
    Write-Host "Retract Completed!"
    }
    else
    {
 Write-Host "Expected: Packaged not installed"
    }
}
foreach ($i in $packages)
{

    Write-Host "Deploying: " + $i
    $solution = (Get-SPSolution | where-object {$_.Name -eq $i.Name})
    if ($solution -eq $null)
    {
 Write-Host "Adding Solution..."
 Add-SpSolution -LiteralPath ($currentDir + $i.Name)
 do
 {
  Write-Host "Waiting for solution to be added..."
  $solution = (Get-SPSolution | where-object {$_.Name -eq $i.Name})
  Start-Sleep -s 5
 }
 until($solution -ne $null)

 Write-Host "Deployment Completed!"
    }
}

No comments:

Post a Comment