.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Scripting SQL Agent Jobs With Powershell

Posted By:      Posted Date: September 15, 2010    Points: 0   Category :Sql Server
Hi,   I have a Sqlserver 2008 and about 120 Sql Agent jobs. We are planning to create new environments and I need to create the same jobs in all the new environments. Now i can script each job individually and then run them on the new servers but i was wondering if there is a Powershell way of looping though all the jobs and generate scripts for them and put them all in one big Sql, so i can just run that 1 script in any new environments that we add to create all the jobs that we have.   I found the below script online and am trying to make changes to it but cannot find the methods to scripts a existing object   # Load SMO extension [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null; # Get List of sql servers to check $sqlservers = Get-Content "$Env:USERPROFILE\sqlservers.txt";   # Loop through each sql server from sqlservers.txt foreach($sqlserver in $sqlservers) {       # Create an SMO Server object       $srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $sqlserver;         # Jobs counts       $totalJobCount = $srv.JobServer.Jobs.Count;       $failedCount = 0;       $successCount = 0;         # For each jobs on the server &n

View Complete Post

More Related Resource Links

How to create SQL-login with permissions for view-only SQL-Agent-Jobs?

Could you please help me with resolving next problem: How to create SQL-login with permissions for view -only SQL-Agent-Jobs (he cannot create, modify or delete)? I am using MS-SQL-Server version: 8.00.194 In other words : how to create in version 2000 (8.00.194) the same as 'SQLAgentReaderRole ' in version 2005 (for more details see http://technet.microsoft.com/en-us/library/ms188283.aspx).

Sql Server Agent stops executing jobs


Hello everyone.  I'm having a problem with the sql server agent occasionally not executing its scheduled jobs, and unless the sql server agent is restarted they will not execute according to their schedule.  I've read many posts on people having problems with running a package manually and then not being able to run it in a job, although that is not my problem since these are jobs that have all run successfully historically, and only until the agent is restarted do they start working again.  It is the strangest thing.....we have many different jobs on this server and all of them will just mysteriously stop being executed.  Two other things of note, the agent and server processes both run on AD accounts, and we receive this error:


SQL Server Scheduled Job 'X' - Status: Failed - Invoked on: 2007-10-27 02:00:00 - Message: The job failed.  Unable to determine if the owner (AD\adacct) of job 'X' has server access (reason: Unable to connect to server - check SQL Server and SQL Server Agent errorlogs).


Any help would be greatly appreciated.

sending mail in SQL using SQL Server Agent Jobs



 I am using SQL Server 2008 and I want to create one job in that.

 Job should be like that it will run any T-SQL and the output of that query

should be mail to me. But I am not able to do this.

Please help me...

SSIS Jobs VS SQL Server Job Agent


Which one of them is better to just run a set of Strored Procedures on a daily basis.

Can I have some Adv and Dis advantages. Please.


SQL Agent Job - PowerShell step giving escape token error



I'm confused as to why I'm getting this error:

The job step contains tokens. For SQL Server 2005 Service Pack 1 or later, you must use the appropriate ESCAPE_xxx macro to update job steps containing tokens before the job can run.).  The step failed.

The job is a single Powershell script step like this:


Get-ChildItem -path "\\server\share-Logs\" -recurse -include *.log | Where-Object {($_.CreationTime -le $((Get-Date).AddDays(-35)))} | Remove-Item


This runs fine from the PS command-line but after testing this part is causing the error: $(Get-Date.AddDays(-35)) , in the Job step

This isn't TSQL or a token - so I don't understand why it doesn't just get put as-is into the PS command-line when the job runs.

Any help appreciated.


Example: Scripting Data with SMO and Powershell

Here's an example of how to script the INSERT statements for data in a table using SMO and Powershell:

# Script INSERTs for given table
  [string] $server,
  [string] $database,
  [string] $schema,
  [string] $table,
  [string] $output_file

# Example call
# C:\SQL\Powershell\Examples\script_data.ps1 ".\sql2005" "tempdb" "dbo" "temp"
# or specify output file
# C:\SQL\Powershell\Examples\script_data.ps1 ".\sql2008" "tempdb" "dbo" "temp" "c:\temp\temp.sql"

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null

$srv = New-Object "Microsoft.SqlServer.Management.SMO.Server" $server
$db = New-Object ("Microsoft.SqlServer.Management.SMO.Database")
$tbl = New-Object ("Microsoft.SqlServer.Management.SMO.Table")
$scripter = New-Object ("Microsoft.SqlServer.Management.SMO.Scripter") ($server)

# Get the database and table objects
$db = $srv.Databases[$database]
$tbl = $db.tables | Where-object {$_.schema -eq $schema-and$_.name -eq $table} 

# Set scripter options to ensure only data is scripted
$scripter.Options.ScriptSchema = $false;
$scripter.Options.ScriptData = $true;

#Exclude GOs after every line
$scripter.Options.NoCommandTerminator = $true;

if ($output_file -gt "") 

Migrating SQL Server 2005 databases, including SQL Agent jobs and SQL users



I should begin to migrate all my data from a SQL Server 2005 (x86) SP3 to another server with SQL 2005 (x64) SP3 installed. About moving the Databases, I think that detach and attach them won't create unexpected problems.

The problems that scare me are:

  1. Migrate the SQL Agent processes. I've created so complex jobs that I'd rather swim across an ocean than rewrite them.
  2. Migrate Users. There are near 70 users with integrated security and each has different mappings to the 40 DBs. Unfortunately there's no domain, so I don't know whether it's possible to copy them without changing their GUIDs.

Does anybody know if my goal is within reach?

Can someone tell me which step to make (and in what order)?

Thank you very much.

SQL Agent Roles and the Ability of an AD Group to Execute Jobs

I would like to give an AD group the ability to execute Agent Jobs using the 2005 Agent roles (SQLAgentUserRole, etc) but you can not assign ownership of a job to a group. I have seen some work arounds and the only one I am considering is using a proxy account. Does anyone have any insight on doing this? This is certainly a fairly common thing to do, give support technicians the ability to run a job.  Running sql server 2005 standard ed, sp3 on a windows server 2003 standard r2 ed, thanks

SQL agent jobs(inside guests) are struck with their past readings


Under HyperV - turning off host with guests running, they are saved with no dataloss. However on restarting the HOST, SQL agent jobs(inside guests) are struck with their past readings as seen in JobActivity Monitor and none of the jobs are running automatically unless you; (a) delete and recreate the schedule. (b) manually run the jobs at once. (c) restart the agent service. [So] Is there some thing available for a fix on this. (tested on SQL 9 SP3 & 10). Guest machines are going for SavedState but there should be something in SQL Server to update the detail (timings) for job execution.


SQL agent jobs(inside guests) are struck with their past readings

Under HyperV - turning off host with guests running, they are saved with no dataloss. However on restarting the HOST, SQL agent jobs(inside guests) are struck with their past readings as seen in JobActivity Monitor and none of the jobs are running automatically unless you; (a) delete and recreate the schedule. (b) manually run the jobs at once. (c) restart the agent service. [So] Is there some thing available for a fix on this. (tested on SQL 9 SP3 & 10)

Give non-sysadmin user access to SQL Agent Jobs


Hi, I have a situation where a group of users (domain ad group) need access to create and edit SQL Agent Jobs. The group can not be sys admin. I tried with the server role SQLAgentOperatorRole. but that doesn't give access to edit all SQL Agent Jobs, only the one that the users owns.

Thanks in advance

Errors when using Proxy/Credentials to execute SQL Agent jobs that access SSIS packages


Running SQL Server 2008, on Windows Server 2008.

I'm having a problem trying to execute a job.  The job has executed successfully when I configure the SQL Agent account (domain account with sysadmin permissions in the instance) as the owner/executor of the job.  However, I want to tighten down security so I'm trying to use a proxy/credential.

Here are the steps I've followed:

1) create a non-privileged SQL account called "SQLJobOwner" that owns the job.

2) create a stored credential (domain account) that has an account on the local machine where the instance resides, and has "log on as batch" permissions.

3) created a login to the instance for the domain account that is stored as a credential, and granted sysadmin permissions to the account.

3) create a new proxy called "SSISProxy", and granted access to the SSIS subsystem.

4) Added job owner "SQLJobOwner" as a principal in the SSISProxy configuration window.

5) changed the job step that executes the SSIS package to "Run as" the "SSISProxy".


When I execute the job, the job fails with the following error:

Unable to start execution of step 1 (reason: Could not get proxy data for proxy_id = 1).  The step failed.

In addition, I get

executing bat files in SQL Server Agent Jobs



there are 2 batfiles running in daily maintenance plans. one, compressing Backups using GZIP and the other deletes old Backup Files.

the delete.bat uses "forfiles" command and successfully deletes files. recenlt the maintenance plan continued to failed and to investigate i foundout that when there are no files met for  the bat files' criteria, it is being recorded as an error and job faliure in SQL Server.

for example, when there are no files to be deleted, the bat file returns a message like "ERROR NO FILES FOUND UNDER THE GIVEN CRITERIA"

this message is interpreted as an error in the SQL Server JOb which is actually not.


do i have a way of handling this kind of errors?


please reply




PowerShell Agent.JobStep for SSIS with one or more configuration file??


Is it possible to script adding a sql agent job for an SSIS package that uses one or more configuration files?  I've spent the better part of the day searching forums and blogs for any examples, but all I can find is just default TSQL or stored proc jobs.  I have most of the script written to pull the appropriate information in, I just do not see how I can specify the configuration files for the job step.  And yes, I've even tried going through Visual Studio accessing that api to see if i can dig out the appropriate object/property to no avail...

Any help would be incredibly appreciated as this would make a huge step forward for our deployment process :)

---- UPDATE ----

I know this sounds odd, but I'm mostly asking because I can't even access a sql 2008 server right now to see what gets put into the step normally for the SSIS Package..I'm assuming all it's really doing in that step is a dtsexec with the appropriate switches, if this is the case, then I can probably just build the command out to pass in multiple configurations...?

Permissions to modify SQL Agent Jobs


Outside of the 3 new roles added to MSDB, does anyone know what or how to allow a user group to have rights to modify SQL Agent Jobs that they do not own without granting dbo or sysadmin rights?

All the permissions I thought would be needed are in SQLAgentOperator/User Roles, but they still can not modify a job they don't own.


John M. Couch

Cutting Edge: Explore Rich Client Scripting With jQuery, Part 2


Achieving cross-browser compatibility for events is no easy task. The jQuery event handling API addresses the differences in event handling across browsers, allowing you to write more predictable JavaScript.

Dino Esposito

MSDN Magazine April 2009

Cutting Edge: Explore Rich Client Scripting With jQuery, Part 1


Thanks to selectors and function chaining, jQuery allows you to write compact, cross-browser code.

Dino Esposito

MSDN Magazine March 2009

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend