Running SharePoint Timer Jobs from PowerShell

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
		}
	}
}
Advertisements
This entry was posted in PowerShell, SharePoint, Timer Jobs. Bookmark the permalink.

3 Responses to Running SharePoint Timer Jobs from PowerShell

  1. venkat says:

    is this code monitors the Job complete?

    I have a requirement where i need to wait till job is completed.

    • gavinbarron says:

      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.

  2. Pingback: Easy Way:Powershell List all timer jobs for a Web application

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s