Tuesday, 7 January 2014

Add Existing List webpart to a Page using PowerShell

# Clear the Screen

  Cls

  # Add the Powershell Ps Snap-in
 
       if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null)
       {
           Add-PSSnapin "Microsoft.SharePoint.PowerShell"
       }

   # Create  variable to check for existance of same list webpart in the page , if i=0  means webpart is not existing

              $i=0
   
    # Get the website url

              $web= Get-SPWeb -Identity "http://sedwdevrtm:22222/sites/demo1/"
   
    # Mention the List name that needs to be added in the page

              $listName = "Test2"
   
    # Specify the page url webpart that needs to be added

              $pageUrl= "http://sedwdevrtm:22222/sites/demo1/SitePages/Home.aspx"

     try
    {

    # Create  New object of type XsltListViewWebPart

        $webpart = New-Object Microsoft.SharePoint.WebPartPages.XsltListViewWebPart
  
        $list=$web.Lists.TryGetList($listName)
       
        #Assign the Webart Listid with Current List Id i.e.. "list id that needs to be added in the page"

         $webpart.ListId = $list.ID

        $webpartmanager=  $web.GetLimitedWebPartManager($pageurl,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

       
         # Loop through all the webparts in the page and , Check if the List  is already Exisiting if i = 1 means list with that id is already exisiting.

        foreach($wpt in $webpartmanager.WebParts)
         {

         # Webpart List id is compared with List id to check for existance of webpart.

                if($wpt.ListId -eq $list.ID)
                {
                 $i=$i + 1
                 break
                }
        }


         if($i -ne "0")

         {

         Write-Host "List is already existing" $list.Title
         }

         else
        {

        write-host "Library is not existing hence Added"

        $webpartmanager.AddWebPart($webpart,"",0)
        }
    }
     
      catch [Exception]
          {

       Write-Host $_.Exception.Message
         }


No comments:

Post a Comment