Today I had to working on a situation where we need to replace a web part with a different one.
First step is to determine what pages have this web part on them. In our environment the web part was only added to the home page of a site. So the script assumes this is the only location of this particular web part
Here is the powershell script I used:
NOTE: I found a bug in that it may return ErrorWebPart. This is due to the httpcontext not being set.
I have modified the code accordingly(reference: http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/607f3980-53c0-4007-bb34-9969ed6ea4fc)
Add-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue
# web application to crawl through
$webApp = "http://webapplication"
# output file for later reviewal
$outputFile = "C:\outputFile.txt"
# webpart full name - not the title
$webPartFQN = "assembly.webpart.name"
write-host "Reading from webapp $($webApp)"
$site = Get-SPWebApplication $webApp | Get-SPSite -limit All
# loop through all the site collection in the web application
foreach($s in $site)
{
#loop through all the webs in the site collection
foreach($web in $s.AllWebs)
{
if ($null -eq [System.Web.HttpContext]::Current){
$isContextNull = $true;
$sw = New-Object System.IO.StringWriter;
$resp = New-Object System.Web.HttpResponse $sw;
$req = New-Object System.Web.HttpRequest "", $web.Url, "";
$htc = New-Object System.Web.HttpContext $req, $resp;
#explicitly cast $web to spweb object else sharepoint will #see it as a PSObject $htc.Items["HttpHandlerSPWeb"] = $web -as [Microsoft.SharePoint.SPweb];
[System.Web.HttpContext]::Current = $htc;
if ($sw -ne $null){
$sw.Dispose()
}
} else {
Write-Host "HttpContext already set";
}
Try{
# get the welcome page in the web's rootfolder.
$defPage = $web.RootFolder.WelcomePage
if( $defPage -eq $null -or $defPage -eq "")
{
#didn't find a welcome page, loop through all pages in rootfolder then
foreach($f in $web.RootFolder.Files)
{
CheckForWP( "$($web.url)/$($f.Name)")
}
}
else
{
#process page to check if the webpart exists
CheckForWP( "$($web.url)/$($defPage)")
}
}Catch{
[Exception]
write-host "Exception thrown while opening web{$($web)} and web part manager."
write-host $_
} }
}
function CheckForWP($page)
{
$pageUrl = $page
# Get the webpart manager to find all the webparts on the page.
$webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
if( $webpartmanager -ne $null)
{
#loop through the web parts
foreach($wp in $webpartmanager.webparts)
{
# get the title and name of the webpart
$wpt = $wp.Title
$wpn = $wp.ToString()
if($wpn.ToLower() -eq $webPartFQN)
{
#write out that I found the webpart in question and the webpart names
write-host "Found on: $($pageUrl)"
$pageUrl | Out-File $outputFile -Append
" $($wpt)" | Out-File $outputFile -Append
" $($wpn)" | Out-File $outputFile -Append
}
}
} else {
write-host "failed to get webartmanager"
}
}
No comments:
Post a Comment