Last active
December 20, 2015 09:30
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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