17 PowerShell and SQL Server Agent

 

The SQL Server Agent executes administrative tasks called jobs. It’s basically the Windows Task Scheduler of SQL Server that enables DBAs to run code on-demand or automatically via a schedule. SQL Agent uses the msdb database to store its information and is available in all editions except for Express. If you’ve spent any time in SQL Server Management Studio, you’re likely very familiar with the SQL Server Agent treeview, as seen in Figure 17.1.

Figure 17.1. Good ol' SQL Server Agent
agentbasic

Agent jobs can run a variety tasks through subsystems that help Agent interact with other components, such as the operating system, PowerShell, Analysis Services, Integration Services and Replication. The list of available subsystems can be viewed in the Job Step Properties tab, as seen in Figures 17.2 and 17.3.

Figure 17.2. A list of SQL Agent subsystems on Windows, including PowerShell
subsystems

Considering PowerShell runs on Linux and SQL Server runs on Linux, you may be wondering if you can run PowerShell-based SQL Agent Jobs on SQL on Linux. The answer at the time of this writing is no, unfortunately.

Figure 17.3. SQL Agent on Linux has strong support for replication, but little else.
linux

While SQL Agent on Linux certainly has its uses, SQL Agent on Windows is where it really shines, primarily because of its support for PowerShell and running external processes. Just check out some example tasks it can do for you in Table 17.1.

17.1 Creating Agent Jobs To Run PowerShell and dbatools

17.2 down the steps

17.2.1 Creating a SQL Server Credential

17.3 Creating a SQL Server Agent Proxy

17.3.1 PowerShell file

17.3.2 Create the SQL Agent Job with a CmdExec Job Step

17.4 Tips

17.4.1 Using Default Parameter Values

17.5 Ensuring that the Agent Job fails when the PowerShell fails

17.5.1 Logging

17.5.2 Execution Policies

17.6 Hands On Lab

sitemap