ngoc
ngoc

Reputation: 63

Use powershell to excecute SQL Agent job

I'm new to PowerShell and need help.
I have a single job in SQL Agent Job and the job name 'RunMeFirst'
I can run this job in SQL server but I want to run in PowerShell command.
Can someone hep and show me step by step what do I need to setup so I can use PowerShell command to run this job.
Thank for your help.

Upvotes: 0

Views: 3971

Answers (1)

Dan Guzman
Dan Guzman

Reputation: 46415

One way to run the job is with the sp_start_job msdb procedure. This can be invoked from PowerShell using .NET SqlClient objects like this example:

$connection = New-Object System.Data.SqlClient.SqlConnection("Data Source=YourServerName;Initial Catalog=msdb;Integrated Security=SSPI")
$command =  New-Object System.Data.SqlClient.SqlCommand("dbo.sp_start_job", $connection)
$command.CommandType = [System.Data.CommandType]::StoredProcedure
($command.Parameters.Add("@job_name", [System.Data.SqlDbType]::NVarChar, 128)).Value = "RunMeFirst"
$connection.Open()
[void]$command.ExecuteNonQuery()
$connection.Close()

Upvotes: 2

Related Questions