By:Joe Gavin | Last Updated: 2019-01-02 || Related Tips:More > Express Edition
ProblemYou need to automate running some SQL, but the is you need to run it directly on an Express Edition of SQL Server that doesn't have the SQL Server Agent we know and love.How can you automate tasks for SQL Server Express?
SolutionPowerShell provides an easy way to script SQL tasks and the native windows Task Scheduler, while not as capable as theSQL Server Agent will work quite nicely for us.
Example Query - Find Latest Backup for All DatabasesFor example, say we want to get an automated report of the last database backup for each database on a server automatically emailed in a format that can be opened with Excel. We'll start with a SQL query to gather the data, demonstrate three different ways to run the query with the Invoke-SqlCmd PowerShell cmdlet, redirect the output to a .csv file, email the .csv and finally run all of it against more than one SQL Servers.
This query from this blog will show us what we need. I've just added one field to show the server name which will come in handy later.
SELECT @@SERVERNAME AS ServerName, sdb.Name AS DatabaseName, COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTimeFROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name
Running it from SQL Server Management Studio (SSMS) shows a nice clean output like this:
Image may be NSFW.
Clik here to view.

The next step is to call it with the PowerShell cmdlet Invoke-SqlCmd.
First example, we'll call the SQL query from the input file C:\scripts\GetLatestBackupDates.sql with the Invoke-SqlCmd -InputFile switch.
# pass sql script$sqlserver = "JGAVIN-L\SQL2016"
Invoke-Sqlcmd -ServerInstance $sqlserver -Database msdb -InputFile "C:\scripts\GetLatestBackupDates.sql"
Second example, we'll call the SQL directly on the command line Invoke-SqlCmd -Query switch.
# call sql direct on command line$sqlserver = "JGAVIN-L\SQL2016"
Invoke-Sqlcmd -ServerInstance $sqlserver -Database msdb -Query "SELECT sdb.Name AS DatabaseName, COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime FROM sys.sysdatabases sdb LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name GROUP BY sdb.Name"
Third example, still using -Query but the SQL is declared in a PowerShell variable that is passed to it.
# declare sql in a variable and pass it to -Query switch$sqlserver = "JGAVIN-L\SQL2016"
$sql="
SELECT sdb.Name AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name
"
Invoke-Sqlcmd -ServerInstance $sqlserver-Database msdb -Query $sql
Running each of these shows all three methods give us the same output.
Image may be NSFW.
Clik here to view.

Email SQL Server Backup Query Results as an Attachment
Next, before we can email an attached file we must create it. The output is piped to a .csv with the Export-Csv, then attach it to an email and send it with Send-MailMessage. We'll stay with our third example to keep it more readable.
Add variables to define a file name, mail server, email from and email to Pipe the output to a .csv thru the Export-Csv cmdlet Use the cmdlet Send-MailMessage to email it as an attachment # declare sql in a variable and pass it to -Query switch$sqlserver = "JGAVIN-L\SQL2016"
$outfile = "$env:TEMP\LastBackupTimes.csv" # name of file to email
$PSEmailServer = "smtp.domain.ext" # mail server name
$emailfrom = "[email protected]" # doesn't have to be real email, just in the form [email protected]
$emailto = "[email protected]"
$sql="
SELECT sdb.Name AS DatabaseName,
COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_date), 101),'-') AS LastBackUpTime
FROM sys.sysdatabases sdb
LEFT OUTER JOIN msdb.dbo.backupset bus ON bus.database_name = sdb.name
GROUP BY sdb.Name
"
# delete old out file if it exists
If (Test-Path "$outfile"){Remove-Item "$outfile"}
# run sql and export to .csv
Invoke-Sqlcmd -ServerInstance $sqlserver -Database msdb -Query $sql | Export-Csv $outfile -NoTypeInformation
# email report file
Send-MailMessage -To $emailto -From "$emailfrom" -Subject "Latest Backup Dates" -Attachments $outfile
Before we schedule it let's make it a little more useful by adding the capability to run this on more than one SQL Server. We just need to do a couple of more things.
Change the $sqlserver variable to an array called $sqlservers and enter the SQL Server names to it quoted and comma separated Add a -Append to the Export-Csv so we don't overwrite the file Save the script as GetLatestBackupDates.ps1 # declare sql in a variable, pass it to -Query switch, export to .csv and send as mail attachmentParam ([array] $sqlservers = @("JGAVIN-L\SQL2016","JGAVIN-L\SQL2017"))
$outfile = "$env:TEMP\LastBackupTimes.csv" # name of file to email
$PSEmailServer = "smtp.domain.ext" # mail server name
$emailfrom = "[email protected]" # doesn't have to be real email, just in the form [email protected]
$emailto = "[email protected]"
$sql="
SELECT @@SERVERNAME AS ServerName, sdb.Name AS DatabaseName, COALESCE(CONVERT(VARCHAR(12), MAX(bus.backup_finish_da