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


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)


$WebPartZoneID = "Topzone"

$WebPartZoneIndex = 0




            Write-Host "Page is already Checkout to " $page.CheckedOutBy.UserLogin


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






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

    "Request Site WebPart SucessfullAdded" + (Get-Date -DisplayHint Date) | Out-File -Append "C:\OutPutLog.txt"

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

No comments:

Post a Comment