【发布时间】:2019-11-14 14:14:25
【问题描述】:
我需要编写一个简单的内务脚本来检查 14 个 SQL Server 的表。 我最终使用了来自this 问题的Adam's 脚本。
但是,在运行时,它会跳过随机数量的服务器的发布结果,然后将它们的查询转储到一个表中,然后单独执行任何剩余的服务器。我做错了什么? (因为我无法评论亚当的回答)
我不介意整理表格中的所有数据并在最后转储,但如果这样更容易完成,那么可以使用服务器名称和结果列。
这是我的脚本,下面的示例输出;
$year = Get-Date -Format yyyy
$servers = gc 'ServerList.txt'
foreach ($server in $servers)
{
try
{
$ServerName = "$server"
$DatabaseName = "DatabaseName"
$Query = "select count(*) from Alarm_Activations where Activation_Date not like '%$year%'"
#$ds = $null -Tried adding this to fix the issue
#Timeout parameters
$QueryTimeout = 120
$ConnectionTimeout = 30
Write-Host ""
Write-Host ""
Write-Host " Checking $server "
#Action of connecting to the Database and executing the query and returning results if there were any.
$conn = New-Object System.Data.SqlClient.SQLConnection
$ConnectionString = "Data Source=$server\sqlexpress;Initial Catalog=DatabaseName;Connect Timeout=30; Integrated security=true;"
$conn.ConnectionString = $ConnectionString
$conn.Open()
$cmd = New-Object system.Data.SqlClient.SqlCommand($Query,$conn)
$cmd.CommandTimeout = $QueryTimeout
$ds = New-Object system.Data.DataSet
$da = New-Object system.Data.SqlClient.SqlDataAdapter($cmd)
[void]$da.fill($ds)
$conn.Close()
Write-Host "Number of activations older than $year :"
$ds.Tables
}
catch
{
Write-Error "Something went wrong. Seems you have to do it manually!"
return
}
}
示例输出
转储表的点似乎是随机的,但通常超过一半的服务器。
我见过的最早的是 Server-5,最新的;服务器 14;
& CheckAlarmActivation.ps1
Checking Server-1
Number of activations older than 2019 :
Checking Server-2
Number of activations older than 2019 :
Checking Server-3
Number of activations older than 2019 :
Checking Server-4
Number of activations older than 2019 :
Checking Server-5
Number of activations older than 2019 :
Checking Server-6
Number of activations older than 2019 :
Checking Server-7
Number of activations older than 2019 :
Checking Server-8
Number of activations older than 2019 :
Checking Server-9
Number of activations older than 2019 :
Checking Server-10
Number of activations older than 2019 :
Column1
-------
0
0
0
3318
1069
4375
8
9357
74
1735
Checking Server-11
Number of activations older than 2019 :
7917
Checking Server-12
Number of activations older than 2019 :
3583
Checking Server-13
Number of activations older than 2019 :
5622
Checking Server-14
Number of activations older than 2019 :
4166
【问题讨论】:
-
我会先用
Write-Output替换Write-Host。据我所知,与主机的交互不是同步的。 -
无关提示:将 conn.Close 放入
finally块中,如下所示:finally { $conn.Close() }原因? PowerShell 不支持 using 语句来确保向连接池发送信号以处理连接。 -
我将所有写主机移到 $ds.Tables 上方,并为 $conn.Close 设置了 finally 块。该脚本现在按预期执行,为每个服务器写入一个结果,然后执行下一个。但是,第一台服务器将其输出为表格,以 Column1 作为标题,并在一行中显示结果。其余的只是打印结果。我认为这是由于我对数据集的处理不当造成的?我也会看看 Brandon McLure 的建议!
标签: sql powershell dataset powershell-5.0