PowerShell Script to Start SQL Job

Following Uses Windows Authentication to connect to the SQL Server called “(Local)” and Start the SQL Job called “test”.

It will throw exception if servername is incorrect, or Job name is incorrect, or if you are trying to start a job that is already running :
e.g. “SQLServerAgent Error: Request to run job test (from User MyDomain\MyUserName) refused because the job is already running from a request by User MyDomain\MyUserName.”

$serverName = “(Local)”
$jobname = “test”

[void][System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SqlServer.Smo”)| Out-Null
$server = new-object “Microsoft.SqlServer.Management.Smo.Server” $serverName
$job = $server.JobServer.Jobs[$jobname]
if ($server.JobServer.Name -eq $null){ throw “Error: [“+$serverName.toUpper()+”] SQL Server does not Exist.”; }
elseif ($job.Name -eq $null){ throw “Error: [“+$serverName.toUpper()+”].Jobs.[“+ $jobname +”] does not Exist.” }
else{try {$job.Start();}
catch {throw $_.Exception.GetBaseException().Message;}