使用powershell访问数据集中的所有行

时间:2016-03-11 15:56:01

标签: powershell dataset

我循环遍历一个sql服务器列表,查询数据并创建一个非常有效的数据集。数据集通过管道传输到csv文件,该文件包含所有行。然后,我尝试从每行创建和排列,然后通过电子邮件发送结果。正在发送电子邮件,但内容仅包含列表中最后一台服务器的记录。

ForEach ($instance in Get-Content "D:\servers\sqlservers2.txt")
{

$SQLServer = "$instance" #use Server\Instance for named SQL instances! 
$SQLDBName = "msdb"
$SqlQuery = "  

Select
@@servername as [Server],  
j.[name] AS [JobName],  
run_status = CASE h.run_status  
WHEN 0 THEN 'Failed' 
WHEN 1 THEN 'Succeeded' 
WHEN 2 THEN 'Retry' 
WHEN 3 THEN 'Canceled' 
WHEN 4 THEN 'In progress' 
END, 
h.run_date AS LastRunDate,   
h.run_time AS LastRunTime 
FROM sysjobhistory h  
INNER JOIN sysjobs j ON h.job_id = j.job_id  
  WHERE j.enabled = 1   
   and j.name not like 'copytosan'
   and j.name not like 'syspolicy%'
   and j.name not like '%log%'
   AND h.instance_id

   IN 

   (SELECT MAX(h.instance_id)  
       FROM sysjobhistory h GROUP BY (h.job_id))
"



$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = 
$SQLServer; Database =   $SQLDBName; Integrated Security = True"


$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd

$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)

$SqlConnection.Close()
#File is created with all rows from dataset
$DataSet.Tables[0] | Out-File D:\servers\myfiles.csv -Append
}
foreach ($line in $dataset.tables[0])
{
$body += $line
}
#  (Out-String -InputObject $body -Width 100)
Send-MailMessage -To Bob@domain.com -from SQLMAIL@domain.com -Subject    Test12345 -body (Out-String -InputObject $body -Width 100) -SmtpServer  mail@domain.com      

1 个答案:

答案 0 :(得分:0)

您需要嵌套第二个循环。这样它就会循环遍历每个表的行而不是最后一个表。

ForEach ($instance in Get-Content "D:\servers\sqlservers2.txt")
{
    # code
    foreach ($line in $dataset.tables[0])
    {
        $body += $line
    }
}