7

Send an email from Powershell based on SQL result

 2 years ago
source link: https://www.codesd.com/item/send-an-email-from-powershell-based-on-sql-result.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Send an email from Powershell based on SQL result

advertisements

Newbie. I have a flat file which I want to SQL-query for a string from within a PowerShell script (example SQL: SELECT * FROM '[LOGFILEPATH]' WHERE Field1 LIKE '%LOGIN%'), and if the query returns any rows the PS script should send an email. I'll have other functions to add later but right now I need to know how to pass the result to PS and send an email accordingly. Thanks.


You can send mail from Sql Server itself, if DBMail is configured. The procedure sp_send_dbmail can send query results as an attachment. Like so,

declare @mailTo varchar(64) = '[email protected]';
declare @subj varchar(64) = 'Subject for message';
declare @fName varchar(64) = concat('QueryResults-', convert(varchar(10), getdate(), 120), '.txt');
exec msdb.dbo.sp_send_dbmail
@recipients = @mailTo,
@subject = @subj,
@query = N'select top(10) column1, column2 from [MyDatabase].[dbo].[SomeTable];',
@attach_query_result_as_file = 1,
@query_attachment_filename = @fName;

The main limitation in this approach is that it will send you a piece of mail even if there are no results. To overcome this, consider, say, adding an if block. Like so,

declare @cnt int = 0;
set @cnt = (select count(column1) from table where <some conditions apply>);
if @cnt <> 0
begin
    exec msdb.dbo.sp_send_dbmail ...
end


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK