Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A small script to kick off a SQL agent job on SQL Server.
Write-Host "Loading connection..." -ForegroundColor Yellow -NoNewline
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
Write-Host "Done." -ForegroundColor Green
#Set the connection string
$SqlConnection.ConnectionString = "Server=,<server name>;Database=<database name>;Integrated Security=True"
#Declare a SqlCommand object
$SqlCommand = New-Object System.Data.SqlClient.SqlCommand
#Set SqlCommand properties
$SqlCommand.CommandText = "exec dbo.sp_start_job N'<job name>'"
$SqlCommand.Connection = $SqlConnection
#Open SqlConnection
Write-Host "SqlConnection opened successfully." -ForegroundColor Green
#Execute stored procedures
$result = $SqlCommand.ExecuteNonQuery()
if ($result = -1) {
Write-Host "Stored procedure executed successfully." -ForegroundColor Green
Write-Host "Error executing the stored procedure" -ForegroundColor Red
#Close connection always
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.