简体   繁体   中英

Why is this powershell code only returning one result when I have multiple results?

I am running a query through powershell. I know I have multiple results from running the query through ssms. Why does the variable only have one result in powershell?

I have used many methods to do this query and I finally got it working but can't get all the results of the query.

[string] $Server= "mochqdb01";
[string] $Database = "MoCApp.Models.Item+ItemDBContext";
[string] $SQLQuery= $("Select smEmail from Items where DateRequested >= dateadd(day,datediff(day,1,GETDATE()),0)");

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SQLQuery
$SqlCmd.Connection = $SqlConnection
$dbname = $SqlCmd.ExecuteScalar()
$SqlConnection.Close()
Write-output "Database is " $dbname

Output: Database is Franziew@marketyyo.com

Should have multiple results. Should I save into an array?

I actually want to save the results into this format.

Send-ToEmail -email "js@marketyyo.com","mb@marketyyo.com";Is this possible?

ExecuteScalar() returns the first column of the first row of the first result set. You need ExecuteReader() . EG

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server=$Server;Database=$Database;Integrated Security=True"
$SqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SQLQuery
$SqlCmd.Connection = $SqlConnection
$rdr = $SqlCmd.ExecuteReader()
while ($rdr.Read())
{
   $smMail = $rdr[0]
   write-output "email is $smMail"
}
$rdr.Close()
$SqlConnection.Close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM