I am a newbie when it comes to Powershell so I'm asking for help. In Sharepoint 2010 I have several document libraries in a single site collection that all start with the name of 'PT-' and in those libraries are specific files that I need to delete like *.xyz. How can I loop through the libraries and remove the files based on the file extension using Powershell?

Any help would be appreciated and let me know if I need to supply more information.

Thanks, Mike

1 Answer 1


Have a look at the below code, I have not done test run of the below code because now I dont have powershell. You can just grasp the logic and idea to achive your requirement using the below code.

Add-PSSnapin "Microsoft.SharePoint.PowerShell"
$siteURL = "Your Site URL" 
$site = Get-SPSite($siteURL) 
foreach($web in $site.AllWebs) 
    $listCounter = $web.Lists.Count 
    for($i=0;$i -le $listCounter;$i++) 
        $list = $web.Lists[$i] 
        if($list.BaseType -eq "DocumentLibrary") { 
        $newList = $web.Lists.item($list.ID);
    $collListItems = $newList.Items; 
        Write-Host $newList
        Write-Host "*********************"
    $countt = $collListItems.Count 
    Write-Host  $countt
    for($intIndex = $countt; $intIndex -gt -1; $intIndex--) 
        if($collListItems[$intIndex].Name.Contains(".your file extension"))
         Write-Host  $collListItems[$intIndex].Name



    Write-Host "-----------------------"
Remove-PsSnapin Microsoft.SharePoint.PowerShell

The above code will loop through all the Document libraries, displays and deletes the specified file.

  • Ok, I think I'm getting to understand what are trying to do but something is off. With your code starting with $countt = $collListItems.Count - 1 it looks like you got the total number of items in the library and are going to traverse it and delete it based on extension however I don't see where $item.name would be assigned to an item in the library. At this point it comes across as a null value and errors out. Thoughts? Thanks, Mike
    – user17559
    Jun 13, 2013 at 22:09
  • Hi Mike, in document libraries, "Name" field is mandatory for all the items in the library, so we will not face null exception. Now I have altered the code, you can make use of it. Jun 14, 2013 at 9:13
  • Karthik, I really appreciate your help with this. This made my life a ton easier. Thanks!
    – user17559
    Jun 19, 2013 at 14:23

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.