Trigger a sqlagent job from Powershell

I am trying to trigger a sql agent job from a powershell script and I want to add powershell script and add it to  task scheduler. Here is where I am stuck.All I am trying to do is check if a new file exists at a specified location. if yes then execute a sql agent job else let me know file not exists

Import-Csv .\*.csv | ForEach { If (Test-Path -Path $_.File) {

--how do I trigger the sqlagent job } Else { Write-Output "No CSV file does NOT exist" } }

August 31st, 2015 5:21pm

This should help.

$Con = new-object System.Data.SqlClient.sqlConnection "server=<servernamehere>;database=msdb;Integrated Security=sspi"
$con.Open()
$cmd = $con.CreateCommand()
$cmd.CommandText = "EXEC dbo.sp_start_job N'<jobnamehere>'"
$cmd.ExecuteReader()
$con.Close()
Free Windows Admin Tool Kit Click here and download it now
August 31st, 2015 6:32pm

You no need to do this kind of overhead for running the agent job.

If you are working with SQL agent that means you are using SQL edition other than Express edition.

You can schedule the agent job in the same was as you can do in task manager.

So that you can avoid scripting in powershell and again calling from task manager.

August 31st, 2015 8:09pm

Hi SqlPUser,

Please check the below link .

http://www.johnsansom.com/script-sql-server-agent-jobs-using-powershell/

Free Windows Admin Tool Kit Click here and download it now
August 31st, 2015 10:37pm

he identity that script is being executed under has to have rights on the SQL Server to start a job. And this is the script .

param (
[string] $instancename,
[string] $db,
[string] $jobname
)
$sqlConnection = new-object System.Data.SqlClient.SqlConnection 
$sqlConnection.ConnectionString = 'server=' + $instancename + ';integrated security=TRUE;database=' + $db 
$sqlConnection.Open() 
$sqlCommand = new-object System.Data.SqlClient.SqlCommand 
$sqlCommand.CommandTimeout = 120 
$sqlCommand.Connection = $sqlConnection 
$sqlCommand.CommandText= "exec dbo.sp_start_job " + $jobname 
Write-Host "Executing Job => $jobname..." 
$result = $sqlCommand.ExecuteNonQuery() 
$sqlConnection.Close()
August 31st, 2015 11:43pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics