Tuesday 29 July 2014

Add WebPart to Page using PowerShell


Below Powershell Script will add Webpart to a page , by reading the Site URL from text file , and 

here we are adding the Webpart to a page by exporting the webpart to our local drive and exported 

webpart will be in xml file and we are writing the xml file to a page.

To add a webpart to a page first we need to check if a page is checked out to any user, if so then act according to your requirement, here in our case we are overriding the checkout and adding the webpart and publishing the same to the page.

Here we are writing the output to textfile instead of writing it on powershell console.

Here "CollabrationURL" is the name of the column in the textfile for SiteURL

cls

asnp "*sh*"

$file=Import-Csv -Path "C:\Manju\SiteUrl.txt"

$web=Get-SPweb -Identity $file.CollabrationURL

[xml]$webpartxml= Get-Content -Path "C:\Manju\WPRequest.xml"

$SR = New-Object System.IO.StringReader($webpartxml.OuterXml)

$XTR = New-Object System.Xml.XmlTextReader($SR)

$err=$null

$WebPartZoneID = "Topzone"

$WebPartZoneIndex = 0

 try
   {

  $page=$web.GetFile("Pages/default.aspx");

  $bool=$page.CheckedOutBy

        if($bool)
        {
            Write-Host "Page is already Checkout to " $page.CheckedOutBy.UserLogin

            $page.UndoCheckOut()

            Write-Host "Page is Over ridded by " $web.CurrentUser.DisplayName
        }

    $page.CheckOut();

    $wmgr=$web.GetLimitedWebPartManager($page,[System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared);

    $webpart=$wmgr.ImportWebPart($XTR,[ref]$err);

    $wmgr.AddWebPart($webpart,$WebPartZoneID,$WebPartZoneIndex);

    $page.CheckIn('dude');

    $page.Publish('Adding request Site Webpart')

    "Request Site WebPart SucessfullAdded" + (Get-Date -DisplayHint Date) | Out-File -Append "C:\OutPutLog.txt"
    
     $SR.Close();
     $XTR.Close();
     $web.Dispose()

    }
    catch
    {
        $ErrorMessage = $_.Exception.Message
   
        "Request Site WebPart Failure" + $ErrorMessage  +  (Get-Date -DisplayHint Date) | Out-File -Append "C:\ErrorLog.txt"
    }




No comments:

Post a Comment