Thursday 26 January 2012

Update a Content Query Web Part using Powershell

Here is a quick little script you can use to change the properties of a content query web part using powershell. I have a whole load of them to do post-deployment and i'm dynamically building the query to do so.

I am using SharePoint 2010 Publishing with a subsite called "news" being deployed with every site. On the home page of each site we have a styled content qeury web part which is being populated from the "news" subsite. I did an export of the content query web part (along with several others) and because i'm doing everything in powershell to automate the deployment, i figured i'd dynamically update the web parts after they have been deployed. That allows me a litttle more control later.


#Set the Site Url and find our publishing page.
$SiteUrl = http://sharepointsite.sharepoint/subsite

$WpWeb = Get-SPWeb $SiteUrl
$PageFolder = $WpWeb.GetFolder("pages")
$Page = $PageFolder.Files Where-Object { $_.Name -eq "default.aspx" }

#Check the page out
$Page.CheckOut()

#Find our web part - the one i'm looking for is "Latest News" and it's visible to all.
$AllWebParts = $WpWeb.GetWebPartCollection($page,"Shared")
$MyWebPart = $AllWebParts Where-Object { $_.Title -eq "Latest News” }

In my case, want to update the WebUrl property to point at my $SiteUrl+"/news" -
just type $MyWebPart if you want to see all of the available properties.

#Update the property. I want to ALWAYS point to the subsite of my current site
$MyWebPart.WebUrl = $siteurl+"/news"
$MyWebPart.ItemLimit = "5"

#Save changes to the web part it's self & Check in and publish -
$AllWebParts.SaveChanges($MyWebPart.StorageKey)
$Page.Update()
$Page.CheckIn("")
$Page.Publish("")

#Because its a publishing page - we'll approve it.
$pweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($WpWeb)
$publishingPage = $pweb.GetPublishingPages() Where { $_.Name -eq "default.aspx"}
$publishingPage.ListItem.File.Approve("Page approved by ps")

#job done
$pweb.dispose()
$WpWeb.Dispose()




Right, thats all for today.
Have Fun!

1 comment:

  1. the syntax of your PowerShell is not quite correct where it calls the Where-Object. You need to pipe to that expression to avoid the error: "Unexpected token 'Where-Object' in expression or statement"

    i.e. $Page = $PageFolder.Files | Where-Object { $_.Name -eq "default.aspx" }

    Useful script though, can see many applications for this!

    ReplyDelete