From the blog

SharePoint Online: HOW TO Programmatically Setup an Alert on a Sub Folder in a Document Library

Alerts can be setup on a document library in SharePoint Online via the UI or programmatically using PowerShell or CSOM.

From the UI, you can setup the alert at the root document library level or at a specific sub folder.

But what if you needed to setup the alert on a specific sub folder in a document library, and you needed to do this for the same named sub folder across multiple document libraries in a site? Doing this manually via the UI would be tedious, especially if you need to do this across several hundred document libraries. A programmatic solution would work better in this scenario.


Programmatic Solution
I am sharing a PowerShell script solution that will enable you to setup an alert on a specific sub-folder across multiple document libraries.

The secret sauce for setting up an alert on a sub folder in document library is CAML Query. You pass the relative path to the folder in the CAML query as shown in the code snippet below.

Thanks to my esteemed colleague, Jonathan Rupp, for his suggestion to take a peek at the $User.Alerts collection’s innards after creating an alert via the UI. That gave me the clue to pass a CAML query with the relative folder path. See screenshot below showing the CAML query for the sub folder within a document library.

Alerts collection for a user — showing the CAML Query filter needed for setting an alert on a sub folder

In the code below, the alert is set on a folder named “Fail” across multiple document libraries. The names of the document libraries are provided in an Excel spreadsheet as shown below. The title of the column in the Excel spreadsheet is “LibraryName.”

Excel spreadsheet containing the names of the document libraries

Credit also goes to Salaudeen Rajack for his article on using PowerShell for setting up an alert in a document library in a site. See link below to his article.

https://www.sharepointdiary.com/2017/10/sharepoint-online-create-alerts-using-powershell.htm

I added the portions shown in the PowerShell code snippet below to loop through an Excel file to set the alert on multiple document libraries, set the alert on a sub-folder in a document library, and to add multiple users/Microsoft 365 groups to the alert.

#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"
    
#Config Parameters
$SiteURL= "https://kirankakanur.sharepoint.com/sites/sandbox/"
$relativePathToSite = "sites/sandbox/"
$subFolderName = "Fail"
$username = "[email protected]"
$password = ConvertTo-SecureString "<your-pw-here>" -AsPlainText -Force 
$alertRecipients = "[email protected]; [email protected]" #multiple users/Microsoft 365 groups separated by semi-colon
$allRecipients = $alertRecipients.Split(";");
$data = Import-Excel "C:\RP\AllDocumentLibraryNames.xlsx" #Uses the ImportExcel PowerShell module

#Setup Credentials to connect
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList ($username, $password)

#Pass Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials 

     if($data)
    {
        foreach($row in $data)
        {
               # get library/list name from excel
               $listName = $row.'LibraryName'                
    
               #Get the List and User Objects
               $List = $Ctx.Web.Lists.GetByTitle($listName)
               #$User = $Ctx.Web.EnsureUser($username)
                                $Ctx.Load($List)
                                #$Ctx.Load($User)
                                $Ctx.ExecuteQuery()


                                $relativePathToFolder =  $relativePathToSite  +  $listName + "/" + $subFolderName

                                

                                $filterCamlQuery = '<Query>
                                                        <Or>
                                                            <Eq>
                                                                <FieldRef Name="ItemFullUrl"/><Value type="string">' + $relativePathToFolder + '</Value>
                                                            </Eq>
                                                            <BeginsWith>
                                                                <FieldRef Name="ItemFullUrl"/><Value type="string">' + $relativePathToFolder + '</Value>
                                                            </BeginsWith>
                                                        </Or>
                                                    </Query>'
 
                                #Create new alert Object and Set its Properties
                                $Alert = New-Object Microsoft.SharePoint.Client.AlertCreationInformation
                                $Alert.List = $List  
                                
                                foreach($alertRecipient in $allRecipients)
                                {   
                                    $User = $Ctx.Web.EnsureUser($alertRecipient)
                                    $Ctx.Load($User)
                                    $Ctx.ExecuteQuery()
                                    $Alert.User = $User
                                     # Add the alert for the user
                                    $AlertGuid = $User.Alerts.Add($Alert)
                                    $User.Update()
                                }
                           
                                $Alert.Title = $libraryTitle + ": Fail"
                                $Alert.AlertFrequency = [Microsoft.SharePoint.Client.AlertFrequency]::Immediate
                                $Alert.AlertType = [Microsoft.SharePoint.Client.AlertType]::List
                                $Alert.DeliveryChannels = [Microsoft.SharePoint.Client.AlertDeliveryChannel]::Email
                                $Alert.Status = [Microsoft.SharePoint.Client.AlertStatus]::On
                                $Alert.EventType = [Microsoft.SharePoint.Client.AlertEventType]::AddObject #Or All
                                #$Alert.Filter = "0" #Anything Changes - Other values: 1, 2, 3
                                $Alert.Filter = $filterCamlQuery

                                # Add the alert for the user
                                #$AlertGuid = $User.Alerts.Add($Alert)
                                #$User.Update()
                                $Ctx.ExecuteQuery()
 
                                Write-host -f Green "New Alert Has been Created!"
            }
    }
}
Catch {
    write-host -f Red "Error Creating Alert!" $_.Exception.Message
}


#Read more: https://www.sharepointdiary.com/2017/10/sharepoint-online-create-alerts-using-powershell.html#ixzz7b0MtbUM5

Leave a Reply

Your email address will not be published.