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.


No comments:

Post a Comment