How do I delete a specific folder from SharePoint using Power Shell script?

Welcome Forums General PowerShell Q&A How do I delete a specific folder from SharePoint using Power Shell script?

Viewing 0 reply threads
  • Author
    Posts
    • #198272
      Participant
      Topics: 4
      Replies: 5
      Points: 62
      Rank: Member

      I have multiple main folders on SharePoint online each with their own sets of sub-folders and files. I need to delete a specific folder (and its full contents including any sub-folders and files) from each of those main folders. The folder has the same name across all main folders, but obviously it does not share the same file path/url. This is what I have come up with so far from the research I have done.  The code for deleting the folder is not even running as far as I can tell.  Any and all help is greatly appreciated.

       

      $url_sharepoint = "https://company.sharepoint.com"
      $library = "Sharepoint Library"
      $deleteFolders = "Folder Name"
      $source_folder = "Network Share:\filepath"
      
      $clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
      $cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Username, $SecurePassword)
      $clientContext.Credentials = $cred
      
      $mylist = $clientContext.web.Lists.GetByTitle($library)
      $clientContext.Load($mylist)
      $clientContext.ExecuteQuery()
      
      #Get name of folder
      $MainFolder = Split-Path $source_folder -Leaf
      
      #upload folder to sharepoint
      $UploadMainFolder = $mylist.RootFolder.Folders.Add($MainFolder)
      $clientContext.Load($UploadMainFolder)
      $clientContext.ExecuteQuery()
      
      $folders = $UploadMainFolder.Folders[$library].SubFolders
      
      Foreach($folder in $folders)
      {
      if ($folder.Name -match $deleteFolders)
      {
      $UploadMainFolder.Folders[$library].SubFolders.Delete($folder)
      Write-Host "Folder has been deleted!"
      }
      else
      {
      Write-Host "Folder has not been deleted!"
      }
      }
Viewing 0 reply threads
  • You must be logged in to reply to this topic.