Book Image

PowerShell for SQL Server Essentials

By : Donabel Santos
Book Image

PowerShell for SQL Server Essentials

By: Donabel Santos

Overview of this book

Table of Contents (15 chapters)
PowerShell for SQL Server Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Implementing Reusability with Functions and Modules
Index

Checking logs


We can use SQL Server Management Objects (SMO) to check the SQL Server error log. The script that picks out anything in the logs that have the words failed or error looks like the following:

$content = ($server.ReadErrorLog() |
Where-Object {$_.Text -like "*failed*" -or $_.Text -like "*error*"})

We can wrap this in code that allows us to send these entries to our DBA (or DBA team) via e-mail. Sending e-mail in PowerShell can be done using the cmdlet Send-MailMessage. Send-MailMessage will accept sender and recipient e-mail addresses, mail server information, subject, content, and, optionally, attachments. The content can either be in text or HTML format. If you are sending an HTML e-mail, you can convert the message into HTML by using ConvertTo-Html. Optionally, you can specify an external CSS with ConvertTo-Html using the -CssUri parameter.

The full script that picks out and e-mails the last 10 entries using a Windows authenticated local account is as follows:

Import-Module...