If you perform the same task more than once, you're probably asking yourself "how can I automate this?" PowerShell provides the tooling to automate monotonous tasks that require manual effort.
Check first to make sure that you have the correctly loaded module for SQL Server. The one that you need is called SQLServer, not the older SQLPS module. SQLPS is now deprecated.
This module is available from Microsoft and will enable you to automate a whole host of things that you are used to doing manually or with complex T-SQL scripts. If you've read my previous blog post, you'll know that the following command is very useful in helping us understand what Cmdlets are available within a module.
Now lets go through 5 quick examples of how we can automate things using the SQL Server PowerShell module.
One of the most interesting features when using PowerShell with SQL Server, is the ability to navigate the objects within SQL Server in a similar way to how you'd navigate the file system in a command prompt.
This is performed by using the function SQLSERVER:
See Figure 1. below for the output from this query.
Figure 1. SQL Server SQL
Once in this structure, you can navigate to the machine name and instance name as appropriate. For example, the path to my default instance on this laptop is SQLSERVER:\SQL\JON-XPS13\DEFAULT
Alternatively, we can use $ENV:ComputerName in place of JON-XPS13 to allow the command to run on any machine. For example SQLSERVER:\SQL\$ENV:ComputerName\DEFAULT
You can then navigate around this structure and become familiar with all the objects within SQL Server.
Here are three methods to show database information.
Use the full path to the Databases folder and display the output.
Use the SMO server object to display the database information.
Figure 2. shows a typical output for databases.
Figure 2. SQL Server Databases
You can output the SQL Server Error Log by using the Get-SqlErrorLog Cmdlet. If the context of the instance has been set, it can be executed in isolation. This will have been set if you navigated to your instance via the directory browsing method explained above.
If you want to pass the instance name as a parameter because it has not been set or you want to query another instance, you can pass the instance name as follows, in this case I'm connecting to a local default instance.
The following example shows you how to query failed logins for the past 24 hours and insert them into a table called x in tempdb.
To retreive the SQL Server agent job history, navigate to the following object, replacing the machine name and instance name as appropriate.
SQLSERVER:\SQL\JON-XPS13\DEFAULT\JobServer
Then run the Get-SqlAgentJobHistory Cmdlet
To return only the job level status, execute the following:
Get-SqlAgentJobHistory|?{$_.StepName -eq "(Job outcome)" }|Select JobName,RunDate,RunStatus