How to iterate through a list of email addresses, and do SQL query based on each one?

Posted on 2009-04-09
Last Modified: 2012-05-06
I have a Powershell script that connects to a SQL database, queries a list of DISTINCT email addresses, and puts them in a variable $data.  (To give a bit more background information, this is for an employee training tracking system I am working on, and this query pulls out the email addresses of all supervisors who have employees with expired training [training that needs to be renewed]).

The next part is what I need help with.

In Powershell, I need to iterate through each supervisor email address in $data, and generate another SQL query that returns a list of expired training items that that supervisor is in charge of.  I do not need help with the SQL query, I can do that.  I need help with the Powershell scripting part of it.

In the end, I need Powershell to email each supervisor a list of expired training items for employees that they are in charge of.  My question is, how do I get Powershell to iterate through the supervisor email addresses, perform a query for each one (WHERE email=''), and pass/store the queried list as a text argument/file so then I can email each supervisor?

If this question is too involved, just forget the final 'emailing each supervisor' part.  If you can get me through the Powershell iterated querying part, I can ask another question about the actual email process later (or maybe figure it out myself).

Thanks in advance!
Question by:KTN-IT
  • 3
LVL 18

Expert Comment

ID: 24109959
If I understand you properly... this is what you do for the filter
$data | ?{$ -eq ""}

Author Comment

ID: 24112465
Not exactly.

For instance, let's say $data is:

Now, I need Powershell to 1) create, 2) execute, 3)email the results of
the following SQL queries:

SELECT items FROM trainingrecords WHERE ExpirationDate <= getdate() AND
SELECT items FROM  [...]  AND SupervisorEmail=''
SELECT items FROM  [...]  AND SupervisorEmail=''
SELECT items FROM  [...]  AND SupervisorEmail=''

I suppose that it would be easiest to do steps 1 through 3 for each email address, that way I would not need to create a separate variable/file to store each result set (I could reuse the same variable with each iteration).

Does that make it a little clearer?  Thanks for commenting.  I realize it is a pretty involved question, but if someone could just get me started in the right direction, it would be a tremendous help.

Author Comment

ID: 24112615
Here's a page I found with information on emailing in Powershell:

$SmtpClient = new-object  

$smtpclient.Host = '' 

$Credentials = new-object System.Net.networkCredential 

$cred = Get-Credential 

$Credentials.domain = "" 

$Credentials.UserName = $cred.UserName 

$Credentials.Password = $cred.GetNetworkCredential() 

$SMTPClient.Credentials = $Credentials 

$smtpclient.Send('', '', 'New Mail', 'A message') 

Open in new window


Accepted Solution

KTN-IT earned 0 total points
ID: 24117855
I have fallen in love with Powershell.  It's the best thing Microsoft has come up with since Excel.  Windows finally has a command-line that equals or surpasses Unix shells.

Here's my solution:
#Thanks to

#for help learning how to query SQL databases from Powershell

function ConnectSQL {

    Param ($server, $query, $database)

    $conn = new-object ('System.Data.SqlClient.SqlConnection')

    $connString = "Server=$server;Integrated Security=SSPI;Database=$database"

    $conn.ConnectionString = $connString


    $sqlCmd = New-Object System.Data.SqlClient.SqlCommand

    $sqlCmd.CommandText = $query

    $sqlCmd.Connection = $conn

    $Rset = $sqlCmd.ExecuteReader()

    ,$Rset ## The comma is used to create an outer array, which PS strips off automatically when returning the $Rset


#Thanks to

function QuerySQL {

    Param ($server, $query, $database = "master")

    $data = ConnectSQL $server $query $database

    while ($ -eq $true) {

        $max = $data.FieldCount -1

        $obj = New-Object Object

        For ($i = 0; $i -le $max; $i++) {

            $name = $data.GetName($i)

            $obj | Add-Member Noteproperty $name -value $data.GetValue($i)





#Thanks to

function sendEmail {

    Param ($recipients, $messagebody)

    $objSMTPClient = new-object System.Net.Mail.smtpClient

    $ = ""

    $objCreds = new-object System.Net.networkCredential

    $objCreds.UserName = ""

    $objCreds.Password = "opensesame"

    $objSMTPClient.Credentials = $objCreds

    $objMailMessage = new-object System.Net.Mail.MailMessage

    $objMailMessage.Subject = "Hello World!"

    $objMailMessage.IsBodyHTML = $true

    $objMailMessage.Body = $messagebody

    $objMailMessage.From = ""

    $recipients | % {$objMailMessage.To.add($_)}



$data = QuerySQL "SQLSERVERNAME" "SELECT EmailAddress FROM Table" "DatabaseName"

#Thanks to for getting me started!

for ($i=0; $i -le $data.length-1; $i++) {

    [string]$strSQL="SELECT Name,ItemName,Expires FROM ExpiredTraining WHERE Email='$($data[$i].EmailAddress)'"

    $data2=QuerySQL "SQLSERVERNAME" $strSQL "DatabaseName"

    sendEmail "" ($data2|convertto-Html)


Open in new window


Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Synchronize a new Active Directory domain with an existing Office 365 tenant
A procedure for exporting installed hotfix details of remote computers using powershell
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now