From time to time you need to execute a given SharePoint timer job now. Sure you could go into Central Admin, find it and run it manually, but where’s the fun in that? Plus sometimes you need to automate this, say in an install scenario.
Luckily it’s dead easy using the SharePoint cmdlets
Heck you can do it in a couple of lines with some pipelining.
$WebApp = Get-SPWebApplication http://mywebappurl $job = Get-SPTimerJob | ?{$_.Name -match $JobName} | ?{$_.Parent -eq $WebApp}
Or if you’d like to be a bit more robust and re-usable:
function StartJobOnWebApp { param([Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)] [Microsoft.SharePoint.PowerShell.SPWebApplicationPipeBind] $WebApplication, [Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1)] [string] $JobName) process { $WebApp = $WebApplication.Read() $job = Get-SPTimerJob | ?{$_.Name -match $JobName} | ?{$_.Parent -eq $WebApp} if($null -ne $job) { Write-Host -ForegroundColor Yellow "Starting "$job.DisplayName Start-SPTimerJob $job } } }
is this code monitors the Job complete?
I have a requirement where i need to wait till job is completed.
No. That code simply starts the job, it doesn’t wait for completion.
Blocking for completion is tricky.
You could monitor the JobHistory collection for an entry for the job that you start and has a StartTime after you kick off your job. That should work as entries are only written to JobHistory once they have completed, regardless of completion status.
Waldek shows the c# for this approach in a post on creating variation programmatically.
Pingback: Easy Way:Powershell List all timer jobs for a Web application