Skip to content

Instantly share code, notes, and snippets.

@jondlm
Last active December 20, 2015 09:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jondlm/6108663 to your computer and use it in GitHub Desktop.
Save jondlm/6108663 to your computer and use it in GitHub Desktop.
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
try
{
#Set SqlCommand properties
$SqlCommand.CommandText = "exec dbo.sp_start_job N'<job name>'"
$SqlCommand.Connection = $SqlConnection
#Open SqlConnection
$SqlConnection.Open()
Write-Host "SqlConnection opened successfully." -ForegroundColor Green
#Execute stored procedures
$result = $SqlCommand.ExecuteNonQuery()
if ($result = -1) {
Write-Host "Stored procedure executed successfully." -ForegroundColor Green
}
}
catch
{
Write-Host "Error executing the stored procedure" -ForegroundColor Red
}
finally
{
#Close connection always
$SqlConnection.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment