Looking for a powershell script that will return a list of all files and their sizes in a document library

Hi all

Looking for the above. I’ve found a few and tried them none of them work. Looking for something that will look at all files in folders and subfolders and subfolders of those.

Many thanks

John

In general most online discussion boards for PowerShell are collaborative. No one is going to write something for you, there are LLMs that can do that for free.

You say “document library” in your title, does this mean you’re talking about SharePoint? Is it SharePoint on prem or SharePoint Online?

And when you say you tried things and none of them worked, can you be more descriptive? Maybe share what you’ve tried and what specifically about it didn’t work?

Otherwise you might as well open your favorite LLM and type your request in to it.

1 Like

HI Courtney

Thanks for the response it’s more hit than miss on these sites so I very much appreciate you’re coming back to me.

I’ve tried LLMs and a number of sites. For example one today is as follows (pertinent info taken out). The export file is just an empty file. This seems to be the norm when I write these scripts.

John

#Config Variables

$SiteURL = “https://abc.sharepoint.com/sites/documents”

$CSVFilePath = “C:\LargeFiles1.csv”

#Connect to PnP Online

#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Connect-PnPOnline -Url “https://abc.sharepoint.com” -Interactive -ClientId " xxxxxxxxxxxx”

#Get all document libraries

$FileData = @()

$DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq “DocumentLibrary” -and $_.Hidden -eq $False}

#Iterate through document libraries

ForEach ($List in $DocumentLibraries)

{

Write-host "Processing Library:"$List.Title -f Yellow



#Get All Files of the library with size > 100MB

$Files = Get-PnPListItem -List $List -PageSize 500 | Where {($\_.FieldValues.FileLeafRef -like "\*.\*") -and ($\_.FieldValues.SMTotalFileStreamSize/1MB -gt 100)}



#Collect data from each files

ForEach ($File in $Files)

{

    $FileData += \[PSCustomObject\]\[ordered\]@{

        Library         = $List.Title

        FileName        = $File.FieldValues.FileLeafRef

        URL              = $File.FieldValues.FileRef

        CreatedBy        = $File.FieldValues.Author.Email

        Created          = $File.FieldValues.Created

        ModifiedBy       = $File.FieldValues.Editor.Email

        Modified         = $File.FieldValues.Modified

        Size            = \[math\]::Round(($File.FieldValues.SMTotalFileStreamSize/1MB),2)

       }

}

}

#Export Files data to CSV File

$FileData | Sort-object Size -Descending

$FileData | Export-Csv -Path $CSVFilePath -NoTypeInformation

when sharing code anywhere online, please remember to format the code so that it’s readable and can be cleanly copied.
If you edit your post, there’s a little + icon at the end of the format buttons for ‘options’ and you can use the “preformatted text”.

From looking at this code sample it looks like you’re using the PnP Powershell module. Is your Sharepoint target a SharePoint online site or an on-prem SharePoint site? This is an important distinction.

HI grey0ut

Okay noted re the formatting.

It’s an online site.

John

k, i don’t see any formatting having taken place.
Since it’s a SharePoint Online site the PnP module should work, but what I would do to try and diagnose what’s going on is do some selective execution in your IDE (Visual Studio Code for example).

#Config Variables

$SiteURL = “https://abc.sharepoint.com/sites/documents”

$CSVFilePath = “C:\LargeFiles1.csv”

#Connect to PnP Online

#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Connect-PnPOnline -Url “https://abc.sharepoint.com” -Interactive -ClientId " xxxxxxxxxxxx”

#Get all document libraries

$FileData = @()

Execute those lines in your IDE and make sure no errors occur in the console.

Then execute this line by itself:

$DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq “DocumentLibrary” -and $_.Hidden -eq $False}

Now, in the shell of your IDE execute $DocumentLibraries and see if it returns anything. If it does not, it means the very first part of this whole thing failed to produce any output (Get-PnPList). That can then be troubleshot on its own.

I did what you suggested when I run $DocumentLibraries I get the following

_TEST RESTORE xxxxxx /TEST RESTORE
Documents xxxxx /Shared Documents
Form Templates xxxxxx /FormServerTemplates
Site Assets xxxxxx /SiteAssets
Site Pages xxxxxx /SitePages
Style Library xxxxxx /Style Library

I tried to click the + at the end of the formatting icons I’m not sure what it’s supposed to do it just made a bunch of the text go all over the place. But this seemed to work.

Summary

This text will be hidden

Summary

This text will be hidden


I don’t think that’s the formatting you’re looking for.
The way I do it is start a new line, and type 3x backtick characters (same key as ~), then make another new line. Everything after will be formatted as code until you end it with another new line containing 3x backticks.

$DocumentLibraries = Get-PnPList

Is the result of:
image

Ok, so you’re saying that $DocumentLibraries contains something. I’m not really sure what “Documents xxxxx /Shared Documents” represents or what type of object it is (I know you redacted stuff for privacy that’s fine).
The next part of the script looks like it’s looping these “lists” and feeding them to Get-PnPListItem
so try this:

Get-PnPListItem -List $DocumentLibraries[1]

that will run the command against the second list that was returned from your previous command.

Good Morning grey0ut!!!

I ran Get-PnPListItem -List $DocumentLibraries[1]

It returned nothing at all

I did it replacing the 1 at the end with a 2 and a 0.

2 returned nothing

0 returned a list of 4 GUIDs.

I tried it with 3, 4, 5 and 6. They all returned different lists with headings Id, Title and GUID with varying entries. 6 returned an error ‘Get-PnPListItem: Cannot bind argument to parameter ‘List’ because it is null’

ok, the next think would be to take your code, and remove all of the backslashes that aren’t supposed to be there. Like on this line:

$Files = Get-PnPListItem -List $List -PageSize 500 | Where {($\_.FieldValues.FileLeafRef -like "\*.\*") -and ($\_.FieldValues.SMTotalFileStreamSize/1MB -gt 100)}

Remove every instance of \ from the line.
Do that for the entire script (there’s more) and then you can try re-running your script in total.

I’ve been running a different script from the original one to produce the results I’ve been posting here. Here’s the script I’ve been running. There’s only one backslash it’s a reference to the locally saved file.

#Config Variables

$SiteURL = “xxxx”

$CSVFilePath = “C:\LargeFiles2.csv”

#Connect to PnP Online

#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Connect-PnPOnline -Url “https://abc.sharepoint.com” -Interactive -ClientId "xxxxxxxxxxxx”

#Get all document libraries

$FileData = @()

$DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq “DocumentLibrary” -and $_.Hidden -eq $False}

ok, that looks fine, though you’re still not formatting your code before posting. If you’re going to talk about code anywhere online you gotta figure out how to format it as a code block before posting.

The code you posted looks functional, but it’s incomplete. $DocumentLibraries is defined but then never used.

So, here’s the deal: I was trying to help you troubleshoot what might be wrong with your script. You said you got this script online, and had also tried LLMs. It’s going to be hard to walk you through debugging code that you found online, and if an LLM wasn’t able to get you what you want then I’ve got some suspicions that some of the problems might be environment or user induced.

My suggestion is to keep slowing working your way through the code, selectively executing blocks, and exploring the output and variables to see if you’re getting close to what you want. Ask an LLM to help fine tune things.

Hi grey0ut

The original code I posted was the following

#Config Variables

$SiteURL = “https://abc.sharepoint.com/sites/documents”

$CSVFilePath = “C:\LargeFiles1.csv”

#Connect to PnP Online

#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Connect-PnPOnline -Url “https://abc.sharepoint.com” -Interactive -ClientId " xxxxxxxxxxxx”

#Get all document libraries

$FileData = @()

$DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq “DocumentLibrary” -and $_.Hidden -eq $False}

#Iterate through document libraries

ForEach ($List in $DocumentLibraries)

{

Write-host "Processing Library:"$List.Title -f Yellow



#Get All Files of the library with size > 100MB

$Files = Get-PnPListItem -List $List -PageSize 500 | Where {($\_.FieldValues.FileLeafRef -like "\*.\*") -and ($\_.FieldValues.SMTotalFileStreamSize/1MB -gt 100)}



#Collect data from each files

ForEach ($File in $Files)

{

    $FileData += \[PSCustomObject\]\[ordered\]@{

        Library         = $List.Title

        FileName        = $File.FieldValues.FileLeafRef

        URL              = $File.FieldValues.FileRef

        CreatedBy        = $File.FieldValues.Author.Email

        Created          = $File.FieldValues.Created

        ModifiedBy       = $File.FieldValues.Editor.Email

        Modified         = $File.FieldValues.Modified

        Size            = \[math\]::Round(($File.FieldValues.SMTotalFileStreamSize/1MB),2)

       }

}

}

#Export Files data to CSV File

$FileData | Sort-object Size -Descending

$FileData | Export-Csv -Path $CSVFilePath -NoTypeInformation

You suggested I use the following which I’ve been using since

#Config Variables

$SiteURL = “https://abc.sharepoint.com/sites/documents”

$CSVFilePath = “C:\LargeFiles1.csv”

#Connect to PnP Online

#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Connect-PnPOnline -Url “https://abc.sharepoint.com” -Interactive -ClientId " xxxxxxxxxxxx”

#Get all document libraries

$FileData = @()

I’m doing the best I can. When you say I’m not formatting the code before posting I don’t know what that means can you point me to where I can learn that? I’ve actually done a ton of coding before but with VBA I thought the transition to powershell would be easier it’s very frustrating but I guess it is what it is.

I already explained how to format code in a previous reply:

put 3x backticks on a line, code after that line, then 3x backticks on a line to close it out.

What I suggested was that you selectively execute lines of the script in an IDE like Visual Studio Code so that you could check the variables as you go and see what’s contained in them, that way you could figure out where the script was failing since you didn’t mention any error messages.
You may very well be doing that but when you said “here’s the script I’ve been running” and then shared what looked like just a portion of the original script I wasn’t sure.

If you’re having trouble using the three backticks that Courtney mentioned twice now, use the icons in the chat window called Preformatted Text and it looks like this </>

image

You can either paste your code, highlight it, then click the button or you can press the button and pasted your code where it says to paste it.

image

unrelated to OP, but for some reason i’ve never had the Preformatted text button on my bar:


I also can’t seem to find the old post that container instructions for code formatting.

It’s part of the welcome post:

https://forums.powershell.org/t/welcome-to-the-new-powershell-forums/7/4

But the interface has changed since that was created. We used to have to point out the button might be hidden under the, now removed, gear icon. You will probably find it if you click the circled + icon.

#Config Variables

$SiteURL = “https://abc.sharepoint.com/sites/documents”

$CSVFilePath = “C:\LargeFiles1.csv”

#Connect to PnP Online

#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

Connect-PnPOnline -Url “https://abc.sharepoint.com” -Interactive -ClientId " xxxxxxxxxxxx”

#Get all document libraries

$FileData = @()

$DocumentLibraries = Get-PnPList | Where-Object {$.BaseType -eq “DocumentLibrary” -and $.Hidden -eq $False}

#Iterate through document libraries

ForEach ($List in $DocumentLibraries)

{

Write-host "Processing Library:"$List.Title -f Yellow

#Get All Files of the library with size > 100MB

$Files = Get-PnPListItem -List $List -PageSize 500 | Where {($_.FieldValues.FileLeafRef -like "*.*") -and ($_.FieldValues.SMTotalFileStreamSize/1MB -gt 100)}

#Collect data from each files

ForEach ($File in $Files)

{

$FileData += \[PSCustomObject\]\[ordered\]@{

    Library         = $List.Title

    FileName        = $File.FieldValues.FileLeafRef

    URL              = $File.FieldValues.FileRef

    CreatedBy        = $File.FieldValues.Author.Email

    Created          = $File.FieldValues.Created

    ModifiedBy       = $File.FieldValues.Editor.Email

    Modified         = $File.FieldValues.Modified

    Size            = \[math\]::Round(($File.FieldValues.SMTotalFileStreamSize/1MB),2)

   }

}

}

#Export Files data to CSV File

$FileData | Sort-object Size -Descending

$FileData | Export-Csv -Path $CSVFilePath -NoTypeInformation

Like that.

Has to be 20 characters long so…

if you are only sharing a short code reference, you can wrap it in single backtick characters.
E.g. this is wrapped in single backticks.
The code you shared is properly formatted which makes it much easier to read and copy/paste out of the forum.
In doing so I could see several unnecessary blank lines, incorrect quotation characters, missing underscores for $_ variables and inappropriate backslash characters.
Here is the code manually cleaned up by me:

#Config Variables
$SiteURL = "https://abc.sharepoint.com/sites/documents"
$CSVFilePath = "C:\LargeFiles1.csv"
#Connect to PnP Online
#Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
Connect-PnPOnline -Url "https://abc.sharepoint.com" -Interactive -ClientId "xxxxxxxxxxxx"
if ($?) {
    Write-Host "Connection succeeded" -ForegroundColor Green
}
#Get all document libraries
$FileData = @()
$DocumentLibraries = Get-PnPList | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $False}
Write-Host "Retrieved $($DocumentLibraries).Count Document Libraries" -ForegroundColor Cyan
#Iterate through document libraries
ForEach ($List in $DocumentLibraries){
    Write-host "Processing Library:"$List.Title -ForegroundColor Yellow
    #Get All Files of the library with size > 100MB
    $Files = Get-PnPListItem -List $List -PageSize 500 | Where-Oboject {($_.FieldValues.FileLeafRef -like "*.*") -and ($_.FieldValues.SMTotalFileStreamSize/1MB -gt 100)}
    Write-Host "Retrieved $($Files).Count list items for $($List).Title" -ForegroundColor Green
    #Collect data from each files
    ForEach ($File in $Files){
        $FileData += [PSCustomObject]@{
            Library     = $List.Title
            FileName    = $File.FieldValues.FileLeafRef
            URL         = $File.FieldValues.FileRef
            CreatedBy   = $File.FieldValues.Author.Email
            Created     = $File.FieldValues.Created
            ModifiedBy  = $File.FieldValues.Editor.Email
            Modified    = $File.FieldValues.Modified
            Size        = [math]::Round(($File.FieldValues.SMTotalFileStreamSize/1MB),2)
        }
    }
}
#Export Files data to CSV File
$FileData | Sort-object Size -Descending
$FileData | Export-Csv -Path $CSVFilePath -NoTypeInformation

I also added in some Write-Host statements so that while it’s executing you can get some sense of the progress.