Tuesday, January 21, 2014

SharePoint 2010: Is web part exist on the page? PowerShell

Hello,

Here is an example of PowerShell function for page to check if the web part exists on it.

function IsWebPartExist($siteUrl, $pageUrl ,$WPName,$WPEmailReport){

  $wpExists = $false
try{
$spSite = Get-SPSite $siteUrl -ErrorAction:Stop
    if($spSite -eq $null){return;}
$spWeb = $spSite.OpenWeb()


  $spWebPartManager = $spWeb.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)

foreach ($webpart in $spWebPartManager.WebParts)
{
   if ($webpart.GetType().Name -eq $WPName)
{
 $wpExists = $true
 return $true
}
}
}
catch{
 $WPEmailReport += New-Object PSObject -Property @{PageURL=$siteUrl;Status="$_.Exception.Message";}
}    
    finally{
$spWeb.Dispose()
$spSite.Dispose()
    }
   return $wpExists
}

Invoke the function

$CurDir = Split-Path -parent $MyInvocation.MyCommand.Definition
 $WPEmailReport = @()

$url = "http://yourpage"

$isSiteWebExists = Get-SPSite $url -ErrorAction:SilentlyContinue

$web = $isSiteWebExists.RootWeb;
$folder = $web.RootFolder;
$isWelcomePageExists = $folder.WelcomePage

$landingPage = $isWelcomePageExists

$isWebPartPDEsist = IsWebPartExist -siteUrl $url -pageUrl $landingPage -WPName "PublishedDocuments" -WPEmailReport $WPEmailReport


if ($isWebPartPDEsist -eq $true)
{ $WPEmailReport +=  New-Object PSObject -Property @{PageURL=$url};}


Write-Host "Writing log files...."
$TimeString = Get-Date -format MM_dd_yyyy__HH_mm
$WPEmailReport | select-object PageURL | Export-csv -path "$CurDir\PDWebPartExist_$TimeString.csv" -notype

No comments:

Post a Comment