Tuesday, 16 October 2012

Delete a List


Add-PSSnapin "Microsoft.Sharepoint.PowerShell" -ErrorAction SilentlyContinue
             
<#
.Synopsis
   Delete Sharepoint list(s) from entire site
.DESCRIPTION
   Delete SharePoint list instance(s) from an entire site, all subwebs
.EXAMPLE
   delete-cSharePointList -ListTitle ListName -webUrl http://wingtipserver
.EXAMPLE
   delete-cSharePointList -ListTitle ListName -webUrl http://wingtipserver -subwebs
.EXAMPLE
   delete-SharePointList -ListTitle_1, listTitle_2, listTitle_n -webUrl http://wingtipserver
.EXAMPLE
   delete-SharePointList -ListTitle_1, listTitle_2, listTitle_n -webUrl http://wingtipserver -subwebs
#>
function delete-SharePointList
{
    [CmdletBinding(SupportsShouldProcess=$true, confirmImpact='High')]
    Param
    (
        # an array of list titles to delete
        [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=0)]
        [System.String[]] $ListTitle,
              # The url of the web the lists reside in
              [Parameter(Mandatory=$true,
                   ValueFromPipelineByPropertyName=$true,
                   Position=1)]
              [ValidateScript({Get-SPSite -Identity $_ | Select-Object -Property Exists -ErrorAction SilentlyContinue})]
              [System.String] $siteUrl,
              # switch to specify whether to delete list from all webs
              [Parameter(ValueFromPipelineByPropertyName=$true, Position=2)]
              [switch] $subwebs
    )

    Begin
    {
              $SPSite = Get-SPSite $siteUrl
    }
   
       Process
    {
              if($subwebs)
              {
                     $SPSite.AllWebs | ForEach-object{
                           deleteList $_ $ListTitle
                     }
              }
              else
              {
                     deleteList $spsite.RootWeb $ListTitle
              }
       }
      
    End
    {
              $SPSite.Dispose()
    }
      
      
}

function deleteList($currentWeb, $listTitle)
{
       $listTitle | ForEach-Object{
              $listInstance = $currentWeb.Lists.TryGetList($_)
                          
              if($listInstance -ne $null)
              {
                     Write-Output ("found a list with the title {0} in web {1}" -f $_, $currentWeb.Url)
             
                     If ($psCmdlet.shouldProcess("$listInstance in web $webUrl", "Delete List"))
                     {
                           $listInstance.Delete()
                           Write-Output ("Deleted list {0} in {1}" -f $_, $currentWeb.Url)
                     }
                     else
                     {
                           Write-Output ("Did not delete list {0} in {1}" -f $_, $currentWeb.Url)
                     }
              }
              else
              {
                     Write-Output ("Failed to find list with title {0} in web {1}" -f $_, $currentWeb.Url)
              }
       }

}