Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

I am trying to iterate over a List and view properties on some items that live within that list, and down one or two levels; this is on a SharePoint 2010 server. So far I have been able to connect to the site and iterate over the Folders and the Items in the top level, but what I want is to be able to iterate over items within the Folders. Out structure is as follows:

site - http://localhost/my_site list - Pages Folder - News ItemB - Article ItemA - Contents

The site is easy enough to connect to, with that I can get the list, Folder and ItemA's and output them so I can see what lives there. What I would like is to be able to view all the ItemB's (and there may be lots of them) under each Folder, there are about 10 Folders in the List with each Folder containing lots of ItemB's.

What's the easiest way to be able to find the Folder and then search under the Folder and get all of its Items to display? My experience with PowerShell and SharePoint in this regard is kind of limited. Any helpful pointers are appreciated.

Here is what I have so far, I'd like to have the part that outputs Content to note the ItemB's.

[string]$url = "http://localhost/my_site"
$totalCount = 0

$site = New-Object Microsoft.SharePoint.SPSite($url) 

$web = $site.OpenWeb()

$list = $web.Lists["Pages"]

foreach ($folderItem in $list.Folders)
{
  Write-Host "Folder: " $folderItem.Name "Count: " $folderItem.Folder.ItemCount
  $totalCount += $folderItem.Folder.ItemCount
}

foreach ($listItem in $list.Items)
{
    Write-Host "    Content: " $listItem.Name "  Folder: " $listItem.Parent
}

Write-Host "Total Items = " $totalCount
$totalFolders = $list.Folders.Count
Write-Host "in a Total Folders of: " $totalFolders
$site.Dispose() 
share|improve this question
    
Michael is this Sharepoint 2007 or 2010? So if i understand you have a folder under a list?? –  Patrick Aug 3 '10 at 0:51
    
Yes, this is Sharepoint 2010, sorry about not going back and editing the post to have that, tried to put it in the tags. –  MichaelF Aug 3 '10 at 13:19

4 Answers 4

up vote 4 down vote accepted

Try this method. It will retrieve items from a specified subfolder in a list

function Get-SPFilesInFolder
{
    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$true)]
    [Microsoft.SharePoint.SPWeb]
    $site,
    [Parameter(Mandatory=$true)]
    [string]
    $listName,
    [Parameter(Mandatory=$true)]
    [string]
    $folderName

    )

    $list = $site.Lists | where{$_.Title -eq $listName} 

    if(!$list)
    {
        Write-Host "List not found"
        return
    }

    $query = New-Object Microsoft.SharePoint.SPQuery
    $query.Folder = $list.RootFolder.SubFolders[$folderName]

    $items = $list.GetItems($query)

    return $items
}

Clear-Host
$gc = Start-SPAssignment

$site = $gc | Get-SPWeb "http://intranet.aabnet.dk"
$items = Get-SPFilesInFolder $site "Documents" "subfolderA"
Write-Host $items
$items | fl url

$gc | Stop-SPAssignment
share|improve this answer
    
The code isnt dynamic, in the sense that it doesnt iterate. I was under the impression from what you described that you needed data from a specific folder, but not the other. If you need all documents, regardless of folders just use the Items collection on the list, as this collection contains all items. With a few editions (hint: take out root folder and feed it folder instead of site) you could make this method recursive and call it for each folder. –  Anders Rask Aug 3 '10 at 18:59
    
Thank you very much, I wasn't clear on how to get the iteration part and the item list linked together, I want to be able to see right now the items in each folder. Once I do that, then I need to do some other more detailed work, but getting this part working was a really hard first step. I appreciate the assist! –  MichaelF Aug 4 '10 at 13:46

I think you are looking for recursive operator. Here is the good link on how to do this.

http://martinbodocky.wordpress.com/2012/03/06/spquery-get-all-items-from-sharepoint-list/

string siteUrl = @”http://xxxxxxx”;

using (SPSite site = new SPSite(siteUrl))

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists["Project Documents"];

     Console.WriteLine(“List: “ + list.Title);

     Console.WriteLine(“ReallyCount: “ + list.ItemCount);

     //First attempting with empty query return only first line of items

     SPQuery spQry = new SPQuery();

     spQry.RowLimit = 300;

     do

     {

           SPListItemCollection items = list.GetItems(spQry);

           Console.WriteLine(“FirstQuery: “ + items.Count);

           spQry.ListItemCollectionPosition = items.ListItemCollectionPosition;

} while (spQry.ListItemCollectionPosition != null);

//First attempting with empty query return all lines of items because you set recursive scope

     spQry = new SPQuery();

     spQry.ViewAttributes = “Scope=\”RecursiveAll\”";

     spQry.RowLimit = 300;

     do

     {

           SPListItemCollection items = list.GetItems(spQry);

           Console.WriteLine(“SecondQuery: “ + items.Count);

           spQry.ListItemCollectionPosition = items.ListItemCollectionPosition;

} while (spQry.ListItemCollectionPosition != null);

}

Console.Read();
share|improve this answer
    
Very nice, I haven't had a need to do this in awhile but this might be worth checking again in the future. –  MichaelF Apr 30 '12 at 14:37
<script type="text/javascript">
        $(document).ready(function () {
        var thisSite = $().SPServices.SPGetCurrentSite(); 
        $().SPServices({    
         operation: "GetListCollection",
         webURL: thisSite,
         listName: "DocLibTreeTest",
           async: false,    
            completefunc: function (xData, Status) {  
            var list = new Array();        
             var $json = $.xmlToJSON(xData.responseXML);         
             $.each($json.Body[0].GetListCollectionResponse[0].GetListCollectionResult[0].Lists[0].List, 
             function (index, value) {             
             if (value.ServerTemplate == 101) {                 
             var listid = value.ID.replace("{", "");                 
             listid = listid.replace("}", "");                 
             var treeID = value.Title.replace(/ /g, "");                 
             var item = {                     "data": value.Title,                     
             "state": "closed",                     
             "attr": { "id": listid, "rel": "list" }                                         
              };                 
              list.push(item);                
               var s = $('#TreeViewTemplate').parseTemplate(item);                 
               $("#docHTML").append(s);                 
               $('#' + treeID + "TreeView").jstree({                    
                types: {                         
                valid_children: ["list"],                         
                max_depth: -2,                         
                max_children: -2,                         
                types: {                             
                list: {                                 
                icon: {                                    
                image: "/_layouts/images/itdl.gif"                                
                 },                                 
                 valid_children: ["folder", "file"],                                 
                 max_depth: -2,                                 
                 max_children: -2,                                 
                 select_node: function (e) {                                     
                 $('#RightArea').append("List</br>");                                     
                 this.toggle_node(e);                                     
                 return false;                                 
                 }                            
                 },                            
                 folder: {                                 
                 icon: {                                     
                 image: "/_layouts/images/folder.png"                                 
                 },                                 
                 valid_children: ["folder", "file"],                                 
                 max_depth: -2,                                 
                 max_children: -2,                                 
                 open_node: function ()
                 { $('#RightArea').append("folder</br>"); return false; }                             
                 },                             
                 file: {                                 
                 icon: {                                     
                 image: "/_layouts/images/page_white.png"                                 
                 },                                
                 valid_children: ["none"],                                 
                 max_depth: 0,                                 
                 max_children: 0,                                 
                 open_node: function () { 
                 $('#RightArea').append("file</br>"); return false; 
                 }                            
                 }                         
                 }                     
                 },                     
                 json_data: {                         
                 data: [                             
                 item                         ]                     
                 },                     
                 plugins: ["themes", "json_data", "types", "ui"]                 
                 });             
                 }
     });         //                var dt = { "Lists": $json.Body[0].GetListCollectionResponse[0].GetListCollectionResult[0].Lists[0].List };                                    
 } 
});
$().SPServices({ operation: "GetAllSubWebCollection",
    webURL: thisSite,
    listName: "DocLibTreeTest",
    async: false,
    completefunc: function (xData, Status) {
        var $json = $.xmlToJSON(xData.responseXML);
        var dt = { "Sites": $json.Body[0].GetAllSubWebCollectionResponse[0].GetAllSubWebCollectionResult[0].Webs[0].Web
        };
        var s = $('#SiteTemplate').parseTemplate(dt);
        $("#siteHTML").html(s);
    } 
});
$().SPServices({
    operation: "GetListCollection",
    webURL: thisSite,
    listName: "DocLibTreeTest",
    async: false,
    completefunc: function (xData, Status) {
        var $json = $.xmlToJSON(xData.responseXML);
        var dt = { "Lists": $json.Body[0].GetListCollectionResponse[0].GetListCollectionResult[0].Lists[0].List };
        var s = $('#ListTemplate').parseTemplate(dt);
        $("#listHTML").html(s);
    }
});


$('#accordion').accordion({
    clearSytle: true,    
                    fillSpace: true });  

        }); 
    </script>
share|improve this answer

Anders that works pretty nice...since I am scanning folders under my Root which is called Pages, which has multiple folders in it, if I try to plug your code in I don't seem to be able to get the content under each folder.

$site = New-Object Microsoft.SharePoint.SPSite($url) 
$web = $site.OpenWeb()
$list = $web.Lists["Pages"]
foreach ($folderItem in $list.Folders)
{
  Write-Host "Folder: " $folderItem.Name "Count: " $folderItem.Folder.ItemCount
  $totalCount += $folderItem.Folder.ItemCount
  $query = New-Object Microsoft.SharePoint.SPQuery
  $query.Folder = $list.RootFolder.SubFolders[$folderItem]
  $items = $list.GetItems($query)
  Write-Host "    Content: "
  $items | fl url
}

Is there something else I would need to do to scan each folder as I cycle through it?

share|improve this answer
    
please use comments on my question instead of opening up a new answer :) –  Anders Rask Aug 3 '10 at 18:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.