1

As the title suggested does anyone know of a powershell script or any other way of getting the count of how many files are within a folder and its subfolders within a library?

I have tried to look but nothing comes close to what I need to do. Any help would be appreciated.

1

Fastest way is to generate file plan:

enter image description here

This will give you an Excel book with 3 sheets, where you'll need the 3rd - that one contains every single folder, it's name, path, and total number of items in it.

1

Not Powershell, but this would fall under "any other way". I wrote a CSR script to recursively crawl down the folder tree in a document library and display the file count in the list view. It counts only files within a folder, and files within all subfolders (but not count the subfolders themselves).

It's not perfect, but it gets the job done.

To get this to work you would need to create a regular Text column called FileCount and add it to a view. Then load jQuery and this script using JSLink, or whatever other method you want to load them, for that LVWP/view. (It is dependent on jQuery so you will have to make sure that loads first.) Make sure to update the URL at the end of the script to reflect the path to wherever you store the script file.

Here's the script:

var DEC = DEC || {};

DEC.FileCountField = (function() {

    function setUpFields(ctx) {
        // early out if item is a file
        if (ctx.CurrentItem.FSObjType != 1) {
            return "";
        }

        var divID = "FileCount_" + ctx.CurrentItem.ID;

        // store the info we need for later after the page has loaded
        DEC.FileCountField.StartFolderUrls.push({
            url: ctx.CurrentItem.FileRef,
            divID: divID
        });

        // set up placeholder spinning gifs until results come in
        var returnHTML = '<div id="' + divID + '"><img src="';
        returnHTML += SPClientTemplates.Utility.ReplaceUrlTokens("~site/_layouts/15/1033/images/progress16.gif");
        returnHTML += '"/></div>';
        return returnHTML;
    }

    function startFileCount() {
        DEC.FileCountField.StartFolderUrls.forEach(function(folderInfo) {
            $.when(getMainFolderCount(folderInfo.url))
                .done(function(totalCount) {
                    if (totalCount === "Error") {
                        var message = "Error";
                    } else {
                        message = totalCount + " files";
                    }
                    $('div[id="' + folderInfo.divID + '"]').html(message);
                });
        });
    }

    function getMainFolderCount(folderURL) {
        // wrap the entire recursive process in a promise
        // so we can accurately control when the process is finished
        var mainDeferred = new $.Deferred();
        var restUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getfolderbyserverrelativeurl('" + folderURL + "')";
        $.ajax({
            url: restUri,
            type: 'GET',
            headers: {
                "accept": "application/json;odata=verbose",
                "content-type": "application/json;odata=verbose",
                "X-RequestDigest": $("#__REQUESTDIGEST").val()
            }
        }).then(function(result) {
            // transform the spFolder object into our
            // custom folder object to begin the recursive
            // subfolder traversal process on it
            var topFolder = new Folder(result.d);
            $.when(topFolder.defer).done(function() {
                mainDeferred.resolve(topFolder.fileCount);
            });
        }).fail(function() {
            mainDeferred.resolve("Error");
        });
        return mainDeferred;
    }

    function Folder(spFolder) {
        var folder = this;
        this.name = spFolder.Name;

        // item count includes both files and subfolders,
        // so we can only calculate the number of actual files
        // after we have retrieved and can count the subfolders
        this.itemCount = spFolder.ItemCount;
        this.fileCount = 0;

        // set up the deferred for this level
        this.defer = new $.Deferred();

        this.subFolderPromises = [];
        this.subFolders = [];

        var getSubfolders = function(subfoldersURI) {
            return $.ajax({
                url: subfoldersURI,
                type: 'GET',
                headers: {
                    "accept": "application/json;odata=verbose",
                    "content-type": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val()
                }
            }).then(function(result) {
                return result.d.results;
            });
        }

        var subFoldersRetrievedCallback = function(subFolderCollection) {
            if (subFolderCollection.length > 0) {
                // store the spFolder objects as our own custom
                // objects to start the recursive process on them,
                // so we can count them and get their sub-file counts later
                subFolderCollection.forEach(function(subfolder) {
                    this.subFolders.push(new Folder(subfolder));
                }, this);
                // store each subfolder's promise so we can wait for all
                this.subFolders.forEach(function(subfolder) {
                    this.subFolderPromises.push(subfolder.defer);
                }, this);
                // when all promises are done we can get each subfolder's file count
                $.when.apply(folder, folder.subFolderPromises).done(function() {
                    calculateFileCount.call(folder);
                });
            } else {
                // if there are no subfolders, the item count must be 100% files,
                // and we know we have reached the bottom of the branch
                this.fileCount = this.itemCount;
                this.defer.resolve();
            }
        }

        var subFolderFailCallback = function() {
            // shrug off the error and continue
            this.defer.resolve();
        }

        var calculateFileCount = function() {
            // this folder's file count consists of all subfolders file counts
            // plus this folder's itemCount minus the number of actual subfolders
            this.subFolders.forEach(function(subfolder) {
                this.fileCount += subfolder.fileCount;
            }, this);
            var thisFolderCount = this.itemCount - this.subFolders.length;
            this.fileCount += thisFolderCount;
            // once we know our file count, we are done
            this.defer.resolve();
        }

        // we need to attempt to get subfolders for this folder
        // to determine if there are any subfolders we need file counts from
        // or if there are no subfolders we are at the bottom of the branch
        $.when(getSubfolders(spFolder.Folders.__deferred.uri)).done(function(results) {
            subFoldersRetrievedCallback.call(folder, results);
        }).fail(function() {
            subFolderFailCallback.call(folder);
        });
    }

    return {
        render: function() {
            SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
                Templates: {
                    Fields: {
                        "FileCount": {
                            View: setUpFields,
                        }
                    }
                },
            });
        },
        StartFolderUrls: [],
        start: startFileCount
    }
})();

RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~site/SiteAssets/Scripts/FileCountFieldRenderer.js"), DEC.FileCountField.render);
DEC.FileCountField.render();

$(window).load(DEC.FileCountField.start);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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