In our project, we have a situation that we need to update the property of a web part. Since our site is in production, we couldn't recreate the site. The web part is on nearly every welcome page and many pages are created, so we could not manually change the property. So I decided to write the Powershell script.
The following is the procedure to update the web part property using Powershell commands.
- Get the site.
$site = Get-SPSite "SiteCollectionURL"
- Since we must do this throughout the site collection, we will go through all the web.
$webcoll = $site->AllWebs;
# Step through each web in site collection
foreach ($web in $webcoll) {
- Now, we need to read the welcome page of each web.
# Get the root folder
$rootFolder = $web.RootFolder
# Get the welcome page
$welcomepage = $rootFolder.WelcomePage
- Once we have the welcome page, get the file and check it out.
$file = $web.GetFile("$welcomepage")
$file.CheckOut()
- Now from the welcome page we will get the webpart manager.
- #more details for SPWeb.GetLimitedWebPartManager.
$wpm = $web.GetLimitedWebPartManager("$welcomepage", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
- Now we have web part manager from the page, we can traverse through all web parts and check for the web part for which we need to set/update the property.
foreach($webpart in $wpm.WebParts) {
if($webpart.MyUniqueProperty) {
if(!$webpart.MyUniqueProperty) {
$webpart.MyUniqueProperty = $MyUniquePropertyValue # Value which needs to be Set/Update
# More details for WebPartManager.SaveChanges()
$wpm.SaveChanges($webpart)
}
}
}
- Check-in and Publish the file - #more details – SPFile.CheckIn().
$file.CheckIn("Updated/Set property of webpart", 1)
$file.Publish("Updated/Set property of webpart")
- Finally, dispose of the site object.
$site.Dispose();
The following is the complete Powershell script.
$site = Get-SPSite "SiteCollectionURL"
$webcoll = $site.AllWebs
# Step through each web in site collection
foreach ($web in $webcoll) {
# Get the root folder
$folder = $web.RootFolder
# Get the welcome page
$welcomepage = $folder.WelcomePage
$file = $web.GetFile("$welcomepage")
$file.CheckOut()
$wpm = $web.GetLimitedWebPartManager("$welcomepage", [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
foreach ($webpart in $wpm.WebParts) {
if ($webpart.MyUniqueProperty) {
if (!$webpart.MyUniqueProperty) {
$webpart.MyUniqueProperty = $MyUniquePropertyValue # Value which need to be Set/Update
$wpm.SaveChanges($webpart)
} # First If
} # Second If
} # Foreach
$file.CheckIn("Updated/Set property of webpart", 1)
$file.Publish("Updated/Set property of webpart")
$site.Dispose()
} # foreach
I hope this will help you. Thanks. Feel free to discuss this.