Tuesday, October 14, 2014

Start SharePoint timer job and wait till job finished using PowerShell

Start or Run SharePoint timer job and wait till the job get completed.

Below PowerShell scripts to start the Document ID timer jobs(Document enable, Document Id Assignment) for specific web application. The function need to parameters one is job name and next one is web application.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

function StartJobOnWebApp
{
    param([string]$WebAppName, [string]$JobName)

    Write-Host " ";
    Get-SPWebApplication;
    Write-Host " ";
 
    $WebApp = Get-SPWebApplication $WebAppName;
 

    ##Getting right job for right web application
    $job = Get-SPTimerJob | ?{$_.Name -match $JobName} | ?{$_.Parent -eq $WebApp}
    if($null -ne $job)
    {
        $startet = $job.LastRunTime
        Write-Host -ForegroundColor Yellow -NoNewLine "Running"$job.DisplayName"Timer Job."
        Start-SPTimerJob $job

        ##Waiting til job is finished
        while (($startet) -eq $job.LastRunTime)
        {
            Write-Host -NoNewLine -ForegroundColor Yellow "."
            Start-Sleep -Seconds 2
        }

        ##Checking for error messages, assuming there will be errormessage if job fails
        if($job.ErrorMessage)
        {
            Write-Host -ForegroundColor Red "Possible error in" $job.DisplayName "timer job:";
            Write-Host "LastRunTime:" $lastRun.Status;
            Write-Host "Errormessage:" $lastRun.EndTime;

        }
        else
        {
            Write-Host -ForegroundColor Green $job.DisplayName"Timer Job has completed.";
        }
    }
    else
    {
        Write-Host -ForegroundColor Red "ERROR: Timer job" $job.DisplayName "on web application" $WebApp "not found."
    }

}

# Input parameter for site collection/web application
$siteUrl = "http://kmsnet:2020/"

$rootSite = New-Object Microsoft.SharePoint.SPSite($siteUrl)

$spWebApp = $rootSite.WebApplication

#run document ID timer job
StartJobOnWebApp  $spWebApp.url "DocIdEnable"

# run Document ID Assignment  timer job
StartJobOnWebApp  $spWebApp.url "DocIdAssignment"


No comments:

Post a Comment