Quantcast
Channel: SharePoint 2013 - Development and Programming forum
Viewing all articles
Browse latest Browse all 7589

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

$
0
0

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 all articles
Browse latest Browse all 7589

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>