-->

17/01/2013

PowerShell - Wait for Retract / Uninstall before Remove

This is a very small tip for SharePoint developers. Basically people hate PowerShell before knowing it. But you will love it once you start using it. Sooooo Comfortable.

So, as a part of PowerShell commands, we have UnInstall-SPSolution command for retracting a SharePoint solution and Remove-SPSolution command to remove the solution from any scope.

When you execute these commands in a sequence in a script (.ps1) file, Usually we end up with an error saying
 Remove-SPSolution : The solution "XXXX.wsp" has been deployed in the farm. Please retract the deployment before removing the solution.You can also use the
-override parameter to forcibly remove the solution, but you will not be able to retract the solution deployment.

So we need to wait until the retraction / uninstallation is completed, to remove solution. But how we can wait in Automated scripts (.ps1) files.

Below is the way to wait . . .

I have 3 SharePoint solutions deployed to farm and I want a single script file which can uninstall and remove the solutions. Look at below PowerShell script.
add-pssnapin "microsoft.sharepoint.powershell"
Set-ExecutionPolicy unrestricted
echo " "
echo "Uninstalling Project1"
$sln = get-spsolution -identity SharepointProject1.wsp 
uninstall-spsolution -identity SharepointProject1.wsp -confirm:$false
echo "Started solution retraction..." 
while($sln.JobExists) { 
echo " > Uninstall in progress..."
start-sleep -s 10 
}
remove-spsolution -identity SharepointProject1.wsp -confirm:$false
echo "Removed Project1"
echo "  "
echo "Uninstalling Project2"
$sln = get-spsolution -identity SharepointProject2.wsp 
uninstall-spsolution -identity SharepointProject2.wsp -confirm:$false
echo "Started solution retraction..." 
while($sln.JobExists) { 
echo " > Uninstall in progress..." 
start-sleep -s 10
} 
remove-spsolution -identity SharepointProject2.wsp -confirm:$false
echo "Removed Project2"
echo "  "
echo "Uninstalling Project3"
$sln = get-spsolution -identity SharepointProject3.wsp
uninstall-spsolution -identity SharepointProject3.wsp -confirm:$false
echo "Started solution retraction..." 
while($sln.JobExists) { 
echo " > Uninstall in progress..." 
start-sleep -s 10 
} 
remove-spsolution -identity SharepointProject3.wsp -confirm:$false
echo "Removed Project3"

Now here is the output.

Task Accomplished.

2 comments:

  1. You need to Set-ExecutionPolicy to unrestricted, before you run the script otherwise it's unlikely to work, unless the script is signed and policy is to allow signed scripts, but then why would you change it?

    ReplyDelete
  2. You dont need the Set-ExecutionPolicy unless you need to!!!!

    This scripts rocks man!!!

    ReplyDelete