Friday, January 31, 2014

Export all the WSP solutions from SharePoint Farm With PowerShell

###############################################################################
## Purpose: Export WSPs from Solution Store to a folder definied by you                           

##    Usage:   .\ExportSolutions.ps1 -ExportPath “C:\Solutions” -Overwrite $true
###############################################################################

[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,Position=1)]
[string]$ExportPath,
[Parameter(Mandatory=$true,Position=2)]
[bool]$Overwrite
)

function LoadSharePointPowerShellEnvironment
{
write-host “Setting up PowerShell environment for SharePoint” -foregroundcolor Yellow
write-host
Add-PSSnapin “Microsoft.SharePoint.PowerShell” -ErrorAction SilentlyContinue
write-host “SharePoint PowerShell Snapin loaded.” -foregroundcolor Green
write-host
}

LoadSharePointPowerShellEnvironment

$FinalPathExists = Test-Path $ExportPath
if($FinalPathExists)
{
$LocalFarm = Get-SPFarm -ErrorAction SilentlyContinue
if($LocalFarm -ne $null)
{
$FarmSolutions = $LocalFarm.Solutions
$Count = 0
foreach($Solution in $FarmSolutions)
{
if($Solution -ne $null)
{
$FinalPath = $ExportPath + “\” + $Solution.Name;
$FileExists = Test-Path $FinalPath
if($FileExists -and -not $Overwrite)
{
## If file exists and user does not want to overwrite, do nothing
}
else
{
Write-Host “Exporting solution to $FinalPath…” -ForegroundColor Yellow
Write-Host
$Solution.SolutionFile.SaveAs($FinalPath);
Write-Host “Exported solution to $FinalPath successfully.” -ForegroundColor Green
Write-Host
$Count++
}
}
}
Write-Host “Exported $Count WSP Solutions to $ExportPath.” -ForegroundColor Green
Write-Host
}
else
{
Write-Error “Local SharePoint farm not found.”
Write-Host
}
}
else
{
Write-Error “Path $ExportPath does not exist, please specify correct path.”
Write-Host
}