The goal for this blog post is to display how easy it is to manage and update SharePoint timerjob through PowerShell.
For this demo I created a Timerjobtest class that inherits from SPJobDefinition with an empty and an overloaded constructor that takes a SPWebApplication as argument and custom property call Message.
The first thing I do is restart the timer service (SPTimerV4) to ensure I’m working with the same version of my DLL as the timer service has loaded.
Then I delete all old versions of my Timerjobtest timerjob, load my custom DLL so I can work with it in my PowerShell script, after that I create a SPSchedule object used later.
Documentation on a valid schedule object:
The type must be a valid SharePoint Timer service (SPTimer) schedule in the form of any one of the following schedules:
- Every 5 minutes between 0 and 59
- Hourly between 0 and 59
- Daily at 15:00:00
- Weekly between Fri 22:00:00 and Sun 06:00:00
- Monthly at 15 15:00:00
- Yearly at Jan 1 15:00:00
Now for some of the core functionality of this script where I’m create an object of my custom SPJobDefinition. The syntax is like this [Fully-Qualified Class Name] $myvarb = New-Object "Fully-Qualified Class Name" -ArgumentList argArry. A nice blog post on creating PowerShell object from .net class is this one http://www.lcbridge.nl/vision/2010/powershell.htm. Then I update the newly created timerjob object, with the schedule object and set a custom property and then I call the update method on the timer job object. At last a get the timer job back from SharePoint and select the custom property Message and then get the timer job again, to run the timerjob ones.
The scripts look like this:
#clear the console, for debug purposes
cls
#Restart the timer service
Restart-Service SPTimerV4
#Delete the old timerjob
Get-SPTimerJob | where { $_.TypeName -eq "Timerjobtest.Timerjobtest" } | % { $_.Delete() }
#Load my custom assembly, so it can be used in my script
[System.Reflection.Assembly]::Load("Timerjobtest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5bfcf02a97af8d35")
#Creating a SPSchedule object from a string
[Microsoft.SharePoint.SPSchedule] $schedule = [Microsoft.SharePoint.SPSchedule]::FromString("Every 10 minutes between 0 and 59")
#Crating an object of my custom SPJobDefinition
[Timerjobtest.Timerjobtest] $timerjobtest = New-Object "Timerjobtest.Timerjobtest" -ArgumentList (Get-SPWebApplication "http://win-ugka6ujlm21/")
#Sets the base properties of SPJobDefinition
$timerjobtest.Schedule = $schedule;
$timerjobtest.Name = "Timerjob test"
$timerjobtest.Title = "Timerjob test"
#Sets my custom property
$timerjobtest.Message = "powershell rocks!!!"
#Updates the timerjob
$timerjobtest.Update($true)
#Gets the Message property value from my timerjob
Get-SPTimerJob -Identity "Timerjob test" | Select "Message"
#Find my timerjob and run it ones
Get-SPTimerJob -Identity "Timerjob test" | Start-SPTimerJob
Happy PowerShelling
No comments:
Post a Comment