Skip to content

Instantly share code, notes, and snippets.

@balbany
Created February 8, 2017 21:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save balbany/3d908670881f12dccc9487e4937a6d93 to your computer and use it in GitHub Desktop.
Save balbany/3d908670881f12dccc9487e4937a6d93 to your computer and use it in GitHub Desktop.
Query SharePoint Changelog in Azure PS Function
Write-Output "PowerShell Timer trigger function executed at:$(get-date)";
if($inTokenBlob){
$persistedToken = Get-Content $inTokenBlob
Write-Output "Persisted token: $persistedToken"
}
#Get creds from environment variables (in Azure app settings)
$secpasswd = ConvertTo-SecureString $env:SPO_P -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($env:SPO_U, $secpasswd)
$controlUrl = $env:SPO_ControlUrl
#Connect to control site
Connect-PnPOnline -Url $controlUrl -Credentials $mycreds
$context = Get-PnPContext
#Get list to check for changes
$list = Get-PnPList -Identity "List Name"
#Create an empty ChangeQuery object
$cq = new-object Microsoft.Sharepoint.Client.ChangeQuery($false,$false)
if($persistedToken){
#We have a persisted change token from the last run - use it to set the starting point for the current run
$lastToken = new-object Microsoft.Sharepoint.Client.ChangeToken
$lastToken.StringValue = $persistedToken
$cq.ChangeTokenStart = $lastToken
}
#Set the ChangeQuery settings (the things/events to check for changes)
$cq.Item = $true
$cq.DeleteObject = $true
#Use the ChangeQuery on the list
$changes = $list.GetChanges($cq)
$context.Load($changes)
Execute-PnPQuery
#Now we have the changes
$changeArray = @()
$delete = $false
foreach ($change in $changes)
{
if ($change.GetType().Name -eq 'ChangeItem')
{
$delete = $true
#Push the list item Id to an array
$changeArray += $change.ItemId
}
}
if($delete){
#Write the changeArray as a comma-separated list to the queue binding
Set-Content -Path $outMsg -Value ($changeArray -join ",")
#Update the persisted change token with the last change processed
Set-Content -Path $outTokenBlob -Value $changes[$changes.Count - 1].ChangeToken.StringValue -Force
Write-Output "Items deleted - message created: $changeArray"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment