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 filepath/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!"
}
}