6

I'm trying to loop all splistitem in a folder of a library. I can get my library and have folder but i'm not able to get the items inside the folder. When i display the listitem for folder, i've the number of folder at root library and inside folder not the splistitem in folder. Here is what i did.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$url = "http://myspurl"
$SPWeb = Get-SPWeb $url
#retrieve list to update
$list = $SPWeb.Lists["myList"]
write-host $list.Title
#loop in lib
foreach($folder in $list.Folders)
{
if($folder.Name -eq "10002")
{
    #this count return me always the number of folder at the root of library and inside folder. and not the splistitem inside folder
    $folder.ListItems.Count
    foreach($item in $folder.ListItems)
    {
        #write-host "TEST"
        #$item = $file.Item
        #write-host "item = "$item.Title
        #$item.Url
    }

}
}

When i'll have splistitem inside folder i've to move it in an other folder depending of a meta

Thanks for your help

1 Answer 1

6

The objects you get from $list.Folders are SPListItems not SPFolders so the ListItems property gives the Lists ListItemCollection not something for the folder.

To get the SPFolder you have to access $folder.Folder.

If what you're working with is a document library, then it's easy just access $folder.Folder.Files and you'll get the files in the SPFolder, then for each file you can get the Item

But if you're working with a list then you have to use a SPQuery to get the listitems in the folder like this:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
$url = "http://myspurl"
$SPWeb = Get-SPWeb $url
#retrieve list to update
$list = $SPWeb.Lists["myList"]
write-host $list.Title
#loop in lib
foreach($folder in $list.Folders)
{
  if($folder.Name -eq "10002")
  {
    $query = New-Object -Type 'Microsoft.SharePoint.SPQuery'
    $query.Folder = $folder.Folder
    $folderItems = $list.GetItems($query)
    foreach($item in $folderItems)
    {
      write-host $item.Title
    }
  }
}
2
  • @perJakobsen I am getting an error as 'Property 'Folder' cannot be found on this object; make sure it exists and is settable' when I execute the below step $query.Folder = $folder.Folder Could you please help me in rectifying this error?
    – Vishal
    Aug 2, 2017 at 7:36
  • Thanks for posting this. I was barking up the Document Library Tree for a day until I read this and now I'm able to do what I need in a List Folder. May 12, 2019 at 1:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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