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

Friday, January 17, 2014

Powershell single-object arrays

If function return a single-object arrays you won't have a Count method in Powershell array.Count

  1. A function that returns an array with a single value might not be seen as an array to the code calling it.  Because of rule one, you can still iterate over it, but it won’t have array properties such as Count.
  2. If you want to guarantee that you get an array from a function, wrap the call with @().
Example 1: In this case $allPubPages variable with have type string.

$allPubPages=@()

$allPubPages = GetAllSitePublishingPages -url $url



Example 2 In this case $allPubPages variable will have type array:

$allPubPages=@()

$allPubPages = @(GetAllSitePublishingPages -url $url)



Function: 
function GetAllSitePublishingPages($url){
$pageArray = @()
filter Get-PublishingPages {
    $pubweb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($_)
    $query = new-object Microsoft.SharePoint.SPQuery
    $query.ViewAttributes = "Scope='Recursive'"
    $pubweb.GetPublishingPages($query)
}
 
if($leave){return $pageArray}
try{
get-spweb $url -ErrorAction:SilentlyContinue | Get-PublishingPages |%{
$pageArray +=  $_.Uri.ToString()
}
}
catch{
return $pageArray
}
#write-host $pageArray
return $pageArray
}

Good luck.