Powershell to delete files from SharePoint Document libraries

爷,独闯天下 提交于 2019-12-25 02:55:36

问题


I am trying to multiple files from multiple SharePoint libraries in SharePoint 2010 on Application server in the farm with the below script:

$list = Get-Content $libpath
$web = Get-Spweb $url
$lib = $web.Lists | where { $_.title -eq $libname }
foreach ($libr in $lib) {
  $file = $libr.Items
  foreach ( $fil in $file) {
    If ($fil.Name -eq $item) {
      $fil.Delete()
    }
  }
}

The problem is that $libr.Items is coming up empty even though the library is not empty.

$libr.Files 
$libr.Files.Name 

All showing up empty as well.

Please help in fixing it. Thank you


回答1:


Try the below code.

Add-PSSnapin Microsoft.SharePoint.PowerShell
$SPWeb = Get-SPWeb "Provide your web here"
$docfiles = $SPWeb.GetFolder("Provide your Document Library name here").Files
foreach ($docfile in $docfiles) {
    Write-host "File Name: " $docfile.Name 
    $docfile.Delete();
}



回答2:


Not sure what this does:

$lib = $web.Lists | where { $_.title -eq $libname }
foreach ($libr in $lib) {

$lib in this case should be a single library, why the foreach? Can I suggest you get the library explicitly then verify that it exists:

$lib = $web.lists.TryGetList($libname)
if ($lib) {
    $items = $lib.items
    foreach ($item in $items) {
        #Your logic here
        #Do you really want to delete? Maybe use $item.Recycle()
    }
}

Also if you know what you want to delete up front, look into batching as you can delete items much faster.



来源:https://stackoverflow.com/questions/55371114/powershell-to-delete-files-from-sharepoint-document-libraries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!