1

I want to write a program using remote event receivers to delete a file within a document library. when itemDeleted event fire the that same file which was in another document library should be removed from the document library.

How can I do this?

1

If you want to trigger file delete event, we need use remote event receiver with CSOM to achieve it. If you only want to delete a file in SharePoint Online document library in client side, we can use PowerShell with CSOM or PnP PowerShell to achieve it.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

Function Remove-SPOFile()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $FileRelativeURL
    )
    Try {
        #Get Credentials to connect
        $Cred= Get-Credential
        $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials

        #Get the file to delete
        $File = $Ctx.Web.GetFileByServerRelativeUrl($FileRelativeURL)
        $Ctx.Load($File)
        $Ctx.ExecuteQuery()

        #Delete the file
        $File.DeleteObject()
        $Ctx.ExecuteQuery()

        write-host -f Green "File has been deleted successfully!"
     }
    Catch {
        write-host -f Red "Error deleting file !" $_.Exception.Message
    }
}

#Set parameter values
$SiteURL="https://tenant.sharepoint.com/sites/lz/"
$FileRelativeURL="/sites/lz/Shared Documents/test.pptx"

#Call the function
Remove-SPOFile -SiteURL $SiteURL -FileRelativeURL $FileRelativeURL

PnP PowerShell:

#Config Variables
$SiteURL="https://tenant.sharepoint.com/sites/lz/"
$FileRelativeURL="/sites/lz/Shared Documents/test.pptx"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PNP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred

    #Try to Get File
    $File = Get-PnPFile -Url $FileRelativeURL -ErrorAction SilentlyContinue
    If($File)
    {
        #Delete the File
        Remove-PnPFile -ServerRelativeUrl $FileRelativeURL -Force
        Write-Host -f Green "File $FileRelativeURL deleted successfully!"
    }
    Else
    {
        Write-Host -f Yellow "Could not Find File at $FileRelativeURL"
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.