2

I'm making a script in Powershell for get all the documents within a document library and its folders and subfolders, I'm doing something like this:

$DocumentLibary = "TestDocuments"
$LibLists = "test"
function GetFiles ($Lists)
{


    foreach ($file in $Lists.RootFolder.Files)
    {   
        Write-Host "`t" $file.Name
    }

#Loop through all subfolders and call the function recursively
     foreach ($SubFolder in $lists.RootFolder.SubFolders)
        {
            if($SubFolder.Name -ne "Forms")
            {  
                Write-Host "`t" $file.Name
                GetFiles ($Subfolder)

            }
        }
}

$rootWeb = $clientContext.Web
$LibLists = $rootWeb.lists.getByTitle($DocumentLibary)
$clientContext.Load($rootWeb)
$clientContext.load($LibLists)

$clientContext.Load($LibLists.RootFolder)
$clientContext.Load($LibLists.RootFolder.Files)
$clientContext.ExecuteQuery()
GetFiles $LibLists

But with this I only get the documents in the root of the document library.

Any idea ? what am I missing?

Thanks!

2 Answers 2

6

Dude, replace your script with this.

$DocumentLibary = "TestDocuments"
$LibLists = "test"

$rootWeb = $clientContext.Web
$LibLists = $rootWeb.lists.getByTitle($DocumentLibary)
$clientContext.Load($rootWeb)
$clientContext.load($LibLists)

$q = New-Object Microsoft.SharePoint.Client.CamlQuery
$q.ViewXml = '<View Scope="RecursiveAll"><Query><Where><Eq><FieldRef Name="FSObjType" /><Value Type="Integer">0</Value></Eq></Where><OrderBy><FieldRef Name="ID" /></OrderBy></Query></View>'
$items = $LibLists.GetItems($q)
$ctx.Load($items)
$ctx.ExecuteQuery()

foreach($item in $items)
{
    #Your code to iterate items here
}
2
function ProcessAllSubfolders($folderCollection)
    {
        foreach ($folder in $folderCollection)
        {
            if ($folder.Subfolders.Count -gt 0)
            {
                ProcessAllSubfolders($folder.SubFolders)
            }

            ProcessFolder($folder.Url)
        }
    }

    # main

    foreach ($folder in $RootFolder.SubFolders)
    {
        if ($folder.Name.StartsWith("a"))
        {
            if ($folder.Subfolders.Count -gt 0)
            {
                ProcessAllSubfolders($folder.SubFolders)
            }

            ProcessFolder($folder.Url)
        }
}

OR

Go to the document library or list. Open Explorer View of the respective document library. Drag & Drop the folder from library to local drive OR Select the folder -> right click -> copy, then paste it on the local drive.

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.