Wednesday, April 18, 2012

PowerShell: Set SharePoint Alerts

I had to come up with a way to set user alerts without sending a notification. I completely forgot about a little function SharePoint provides, which I will post about tomorrow.
My first idea was to just use PowerShell. In the end I came up with two scripts, unfortunately the second one just won't work. But I will post it anyway, maybe it helps someone to get an idea on how to work on the subject.

The first script will get you the user who got the task assigned to. I will only take a look at the last one modified, because my workflow runs everytime an item is created or changed.

## Get user who is assigned to task
$TaskList = $web.lists["Tasks"]
$item = @($TaskList.items | Sort-Object {$_.Modified} -Descending)[0]
$users = $item["Assigned To"].split("#")
$var1 = $users[1]
$var2 = $item
The second one is the one I can't get to work. Maybe someone can sort it out and work with it. I checking the list "Tasks", where I publish all tasks and assign them. Then I want to add an alert, called "Custom Alert", but only on the last modified item.


##########################################
## Create an alert without notification ##
##########################################
$web = Get-SPWeb("YOURWEB)
$TaskList = $web.lists["Tasks"]$alerts = $web.Alerts
$user = $var1
$item = $var2
###################
## Set new alert ##
###################
$setAlert = $web.Alerts.Add()
$setAlert.Title = "Custom Alert"
$setAlert.AlertType = [Microsoft.SharePoint.SPAlertType]::Item
$setAlert.Item = @($TaskList.items | Sort-Object {$_.Modified} -Descending)[0]$setAlert.DeliveryChannels = [Microsoft.SharePoint.SPAlertDeliveryChannels]::Email
$setAlert.EventType = [Microsoft.SharePoint.SPEventType]::Add
$setAlert.AlertFrequency = [Microsoft.SharePoint.SPAlertFrequency]::Immediate
$setAlert.Update()
Maybe you are wondering why I'm using names such as "$var1". Well, this is because of a tool called "Nintex Workflow". They provide the function to store values through your workflow, but the names are "$varX".

No comments:

Post a Comment