Iterating through all Document Libraries, Folder and Item using Powershell

Hi,

In order to retrieve all document libraries, get list of folder and nested folder and list document within library and folder, following script generate list. Add site name and file name to save result.

Here is the PowerShell script which can get you Files-Folders-Libraries:

#Get all lists in farm
Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Get the Site collection
$Site= Get-SPSite http://sharepointsite

$outputPath = “c:\Portallist.csv”

Function GetMyFiles($Folder)
{

Write-Host “+in : “$Folder.Name
foreach($file in $Folder.Files)
{
Write-Host “`t” $file.Name
Add-Content -Path $outputPath -Value  ”                     File Name : $($file.Name)”

}

#Loop through all subfolders and call the function recursively
foreach ($SubFolder in $Folder.SubFolders)
{
if($SubFolder.Name -ne “Forms”)
{
Write-Host “`t” -NoNewline
Add-Content -Path $outputPath -Value  ”           Folder Name : $($SubFolder.Name)”
GetMyFiles($Subfolder)

}
}

}
#Loop throuh all Sub Sites
foreach($Web in $Site.AllWebs)
{
Write-Host “—————————————————–”
Write-Host “Site Name: ‘$($web.Title)’ at $($web.URL)”
Add-Content -Path $outputPath -Value  “Website : $($web.Title)”
foreach($list in $Web.Lists)
{
#Filter Doc Libs, Eliminate Hidden ones
if(($List.BaseType -eq “DocumentLibrary”) -and ($List.Hidden -eq $false) )
{
Write-Host “——————————————-” “+” $List.RootFolder
Add-Content -Path $outputPath -Value  ”         Library : $($List.RootFolder)”
GetMyFiles($List.RootFolder)

}
}
}

5 thoughts on “Iterating through all Document Libraries, Folder and Item using Powershell

  1. This was super handy!! I was wondering if there is a way to specify (based on the document library name) to delete all files (without deleting the sub folders) any idea how I might do that?
    Thanks!

    Like

Leave a comment