Fred_Brown
Fred_Brown

Reputation: 1

How to delete files from Sharepoint with exclusions list using Powershell

I’m trying to delete certain files from a Sharepoint folder, however no matter what I try, I cannot get it to delete. I have an exclusions list, for the names of pictures that should not be deleted. I have attached one of many tries. Anyone know what to do? The exclusionslist and the loop can write out the names to delete without any problems, and the below code gives no error-codes.



$siteurl = “https://sharepoint.com/sites/Some/Sharepoint/Folder”
$username = “AdminAccount”
$securePassword = ConvertTo-SecureString “MuchSecurePassWord” -AsPlainText -Force
$O365Credential = New-Object System.Management.Automation.PsCredential($username, $securePassword)
$count = 0
$exclusions = import-csv “Downloads\exclusions.txt”
$excounter = $exclusions.Count
write-host “Files to not delete $excounter”
Connect-PnPOnline -Url $siteurl -Credentials $O365Credential

        $items = Get-PnPFolderItem -FolderSiteRelativeUrl "/Picture Folder/Test" -ItemType File
        
        $ListItemCount = $items.Count
        Write-Host $ListItemCount
        $Found = 0
        foreach ($item in $items)
        {
            foreach ($User in $exclusions)
                {
                    #Write-Host $item.Name " " $User.User
                    if ($item.Name -eq $User.User)
                        {
                          #  Write-Host $item.Name " " $User.User
                            $Found = 1
                        }
                }
            if($Found -eq 0)
                {
                    $Name = $item.Name
                    Write-host "Delete: " $item.Name $Found
                    $item.DeleteObject()


  }
            $Found=0
            
        }


I'm hoping to delete photos, that are not on the exclusions list.

Upvotes: 0

Views: 88

Answers (1)

Piotr Sulowski
Piotr Sulowski

Reputation: 161

Instead of:

$item.DeleteObject()

Use:

Remove-PnPFile -ServerRelativeUrl $item.ServerRelativeURL

Docs: https://pnp.github.io/powershell/cmdlets/Remove-PnPFile.html

Upvotes: 1

Related Questions