Pages

Search This Blog

Wednesday, April 1, 2015

Deleting number of sub sites recursively in SharePoint

Deleting number of sub sites recursively in SharePoint

(Enter the Text File Path that contains Name of Sites to be cleared)

function RemoveSPWebRecursively($web)
{
    $subwebs = $web.Webs
    foreach($subweb in $subwebs)
    {
        RemoveSPWebRecursively($subweb)
        $subweb.Dispose()
    }
    Remove-SPWeb $web -Confirm:$false
}


Write-Host
Write-Host

write-host "Enter the SharePoint Site URL : "
[string]$URL = Read-Host
[string]$WebURL =  $URL.Trim()


$objSite = Get-SPWeb $WebURL -ErrorAction SilentlyContinue


if($objSite -eq $null)
{
               Write-Host
               Write-Host "Site URL not correct or Site does not extsts. Re-run the script with correct URL." -foregroundcolor Red
               Read-Host
}
else
{
        Write-Host
        Write-Host
           write-host "Enter the Text File Path that contains Sites list to be deleted : "
        [string]$FilePathTmp = Read-Host
        [string]$FilePath =  $FilePathTmp.Trim().Replace('"','')
        $Projects = Get-Content -Path $FilePath
        if($Projects -eq $null)
        {
            Write-Host
               Write-Host "Sorry! Unable to get contents from file." -foregroundcolor Red
               Read-Host
        }
        else
        {
            Write-Host
            write-host  "["  $Projects.count  "] Project(s) found in file. " -foregroundcolor Green
            Write-Host
            $TotalInFile=$Projects.count
            $TotalInWeb =$objSite.Webs.Count
            [int]$TotalDeleted=0

            if( $Projects.count -gt 0)
            {
                foreach ($ProjectSite in $Projects)
                {
                    if($ProjectSite -ne $null)
                    {
                        [bool]$SiteFound =$false;
                       
                        $ProjectSite=$ProjectSite.Trim()

                        for ($i = 0; $i -lt $objSite.Webs.Count; $i++)
                        {
                            $subSite = $objSite.Webs[$i];
                            if($subSite -ne $null)
                            {
                              if($subSite.Title -eq $ProjectSite)
                              {
                                $SiteFound =$true;
                                write-host "FOUND Project Site : " $ProjectSite -foregroundcolor Yellow
                                if( $subSite.Webs.Count -gt 0)
                                {
                                    RemoveSPWebRecursively $subSite
                                }
                                else
                                {
                                    Remove-SPWeb $subSite -Confirm:$False
                                }
                                $TotalDeleted=$TotalDeleted + 1
                                write-host "Project Site : " $ProjectSite " deleted successfully" -foregroundcolor Green
                                break
                              }
                            }
                            else
                            {
                                write-host "Site was NULL at : " $i -foregroundcolor Red
                            }
                        }

                        if($SiteFound -eq $false)
                        {
                            write-host "NOT FOUND Project Site : " $ProjectSite -foregroundcolor Red
                        }
                    }
                }
                <#
                foreach($subSite in $objSite.Webs)
                      {
                    foreach ($ProjectSite in $Projects)
                    {
                        if($ProjectSite -ne $null)
                        {
                            $ProjectSite=$ProjectSite.Trim()
                            if($subSite.Title -eq $ProjectSite)
                            {
                                write-host "Found Project Site : " $ProjectSite -foregroundcolor Green
                            }
                        }
                    }
                             $subSite.Dispose()
                      }#>

                Write-Host
                Write-Host "Sites Deleted Sucessfully....." -foregroundcolor Yellow
                Write-Host
                Write-Host "Total Sites Found in File to be deleted :  " $TotalInFile -foregroundcolor Green
                Write-Host "Total Sites Found in Web Application :  " $TotalInWeb -foregroundcolor Green
                Write-Host "Total Sites Deleted :  " $TotalDeleted -foregroundcolor Green

                Write-Host
                Write-Host "Press Enter to exit." -foregroundcolor Yellow
                   Read-Host
            }
            else
            {
                Write-Host
                Write-Host "No Sites list found in file.... Press Enter to exit." -foregroundcolor Red
                   Read-Host
            }
           
        }
        $objSite.Dispose()
}





Remove all items from a List in SharePoint through PowerShell


We can use below script to clean data from multiple lists in a SharePoint site. This could be very helpful while developing solutions in SharePoint as we may need to clean the data many times during development. This script requires path to a text file which contains the list names ( each name should be in a new line ).

Copy paste below script in a text file and rename the file extension to - *.ps1 

Write-Host
Write-Host

write-host "Enter the SharePoint Site URL : "
[string]$URL = Read-Host
[string]$WebURL =  $URL.Trim()


$objSite = Get-SPWeb $WebURL -ErrorAction SilentlyContinue


if($objSite -eq $null)
{
               Write-Host
               Write-Host "Site URL not correct or Site does not extsts. Re-run the script with correct URL." -foregroundcolor Red
               Read-Host
}
else
{
        Write-Host
        Write-Host
           write-host "Enter the Text File Path that contains Name of Lists to be cleared : "
        [string]$FilePathTmp = Read-Host
        [string]$FilePath =  $FilePathTmp.Trim().Replace('"','')
        $ListNames = Get-Content -Path $FilePath
        if($ListNames -eq $null)
        {
            Write-Host
               Write-Host "Sorry! Unable to get contents from file." -foregroundcolor Red
               Read-Host
        }
        else
        {
            Write-Host
            write-host  "["  $ListNames.count  "] List Name(s) found in file. " -foregroundcolor Green
            Write-Host
            if( $ListNames.count -gt 0)
            {
                [bool] $found=$false
                foreach ($ListName in $ListNames)
                {
                    if($ListName -ne $null)
                    {
                        $list = $objSite.lists | where {$_.title -eq $ListName}
                        if($list -ne $null)
                        {
                            $found=$true
                            Write-Host $ListName " Found ...." -foregroundcolor Green
                            Write-host "---- List $($list.title) has $($list.items.count) entries"
                            $items = $list.items
                            foreach ($item in $items)
                            {
                                $list.getitembyid($Item.id).Delete()
                            }
                            Write-Host "---- List " $ListName " cleared successfully...." -foregroundcolor Green
                        }
                        else
                        {
                            Write-Host
                            Write-Host $ListName " NOT FOUND in current site...." -foregroundcolor Red
                        }
                    }
                }
                if($found -eq $true)
                {
                    Write-Host
                    Write-Host "Lists Cleared Sucessfully.... Press Enter to exit." -foregroundcolor Yellow
                       Read-Host
                }
            }
            else
            {
                Write-Host
                Write-Host "No List Name found in file.... Press Enter to exit." -foregroundcolor Red
                   Read-Host
            }
           
        }
        $objSite.Dispose()
}



PowerShell script for deploying multiple WSP solutions

In case of big SharePoint Farms with large application domain we need to deploy multiple solutions, Doing it manually will be a lot tough and time consuming task. So a more manageable way could be to create a PowerShell script, that runs on the Farm to deploy the listed wsp solutions. I created one of such solution for a client who had around 50-60 such solutions. Below is the script that you can use to deploy wsp's solutions to SharePoint Farm. This script should be placed inside a folder along with the wsp solutions which needs to be deployed. 

Copy-Paste the below script in a text file and rename its extension to - *.ps1


function LoadSharePointPowerShellEnvironment
{
       write-host
       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
}

function DeploySolution($packageName, $packagePath, $WebAppUrl)
{
         $spAdminServiceName = "SPAdminV4"
         #check if solution already exists
         $solution = Get-SPSolution $packageName -ErrorAction SilentlyContinue
         if ($solution -ne $null)
         {
            #Write-Host
               #Write-Warning "The solution $packageName already exists. Press Enter if you want to deploy that solution,
               #else first uninstall the solution and re-run the exe."
               #Read-Host
         #Deploy the solution
         if ($solution.Deployed)
               {
            Write-Host
               Write-Host " $packageName Already deployed... " -foregroundcolor Red
         }
         else
         {
                 if (!$solution.ContainsWebApplicationResource)
                 {
                      Write-Host "Deploying solution $packageName to the Farm..."
                      $solution | Install-SPSolution -GACDeployment -Force -Confirm:$false
                 }
                 else
                 {
                      if ($WebAppUrl -eq $null -or $WebAppUrl.Length -eq 0)
                      {
                        Write-Warning "The solution $packageName contains web application resources but no web applications were specified to deploy to."
                        return
                      }
                      else
                      {
                        Write-Host "Installing solution $packageName to WebAppUrl"
                        $solution | Install-SPSolution -GACDeployment  -WebApplication $WebAppUrl -Force -Confirm:$false
                      }
                 }

                 Write-Host
                 Write-Host "starting admin service...(this may take few minutes to complete)" -foregroundcolor Yellow
                 Stop-Service -Name $spAdminServiceName
                 Start-SPAdminJob -Verbose
                 Start-Service -Name $spAdminServiceName

                 #Block until we're sure the solution is deployed.
                 do { Start-Sleep 2 } while (!((Get-SPSolution $packageName).Deployed))
        
                 Write-Host
                 Write-Host " $packageName Deployed Sucessfully... " -foregroundcolor Green
          }
         }
         else
         {
              #Add the solution
              #Write-Host
              #Write-Host "Adding solution... $packageName..." -foregroundcolor Yellow
              #$solution = Add-SPSolution $packagePath
        Write-Host "Solution Not Found ... $packageName..." -foregroundcolor Red
         }

        
}

#
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#                                                                    Deploy the package
# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#


LoadSharePointPowerShellEnvironment

Write-host "Deploying Solution..." -foregroundcolor Yellow

Write-Host
write-host "Enter the Web Application Url where you need to deploy the solution..."
[string]$Url = Read-Host
[string]$WebAppUrl =  $Url.Trim()

$objSite = Get-SPSite $WebAppUrl -ErrorAction SilentlyContinue
if($objSite -eq $null)
{
       Write-Host
       Write-Host "Web Application Url not correct or Web application doesnot extsts. Re-run the exe with correct url." -foregroundcolor Red
       Read-Host
}
else
{
     $dir = $(gl)
     $list = Get-ChildItem $dir | where {$_.extension -eq ".wsp"}
     $currentDir = Get-Location
     foreach($my_file in Get-ChildItem $list)
     {
        write-host $my_file.Name
           [string]$packageName = $my_file.Name
        [string]$packagePath = $currentDir.Path + "\" + $packageName
        DeploySolution $packageName $packagePath $WebAppUrl
     }
}





PowerShell script for adding multiple WSP solutions

In case of big SharePoint Farms with large application domain we need to add multiple solutions, Doing it manually will be a lot tough and time consuming task. So a more manageable way could be to create a PowerShell script, that runs on the Farm to add the listed wsp solutions. I created one of such solution for a client who had around 50-60 such solutions. Below is the script that you can use to add wsp's solutions to SharePoint Farm. This script should be placed inside a folder along with the wsp solutions which needs to be added. 

Copy-Paste the below script in a text file and rename its extension to - *.ps1



$dir = $(gl)
 $list = Get-ChildItem $dir | where {$_.extension -eq ".wsp"}
 foreach($my_file in Get-ChildItem $list)
 {
       write-host $my_file.Name
       $currentDir = Get-Location
       [string]$packageName = $my_file.Name
        $solution = Get-SPSolution $packageName -ErrorAction SilentlyContinue
         if ($solution -ne $null)
         {
            Write-Host
               Write-Host "The solution $packageName already exists." -foregroundcolor Red
         }
         else
         {
              [string]$packagePath = $currentDir.Path + "\" + $packageName
              Write-Host
              Write-Host "Adding solution... $packageName..." -foregroundcolor Yellow
              $addedsolution = Add-SPSolution $packagePath
        if ($addedsolution -ne $null)
        {
            Write-Host "Solution added successfully... $packageName..." -foregroundcolor Green
        }
        else
        {
            Write-Host "ERROR in adding solution... $packageName..." -foregroundcolor Red
        }
         }
 }