我使用PowerShell来查询列表从SQL数据库
- 取IP地址从IP地址的列表
- 将其插入到SQL查询地址
- 输出结果
到目前为止,该代码仅适用于包含一个IP地址的情况。如果我包含多个脚本无限期挂起
此代码似乎是正确的,应该修复哪些内容?
$file = Get-Content C:\list.txt
$conn.Open()
foreach ($k in $file){
write-host $k
$sql = "SELECT dbo.sem_computer.COMPUTER_NAME,[IP_ADDR1_TEXT],(dbo.SEM_AGENT.FREE_DISK/1073741824)as 'Free Disk Space (GB)',
(dbo.SEM_COMPUTER.DISK_TOTAL/1073741824) as 'Total Disk Space (GB)',
(dbo.SEM_AGENT.FREE_MEM/1073741824) as 'Free Memory (GB)', (dbo.SEM_COMPUTER.MEMORY/1073741824) as 'Total Memory (GB)',
dbo.SEM_COMPUTER.OPERATION_SYSTEM,NAME, SEM_AGENT.MAJOR_VERSION
FROM dbo.sem_computer, [dbo].[V_SEM_COMPUTER], dbo.IDENTITY_MAP, dbo.SEM_CLIENT, dbo.SEM_AGENT
WHERE [dbo].[V_SEM_COMPUTER].COMPUTER_ID = SEM_COMPUTER.COMPUTER_ID
AND dbo.SEM_CLIENT.GROUP_ID = IDENTITY_MAP.ID
AND dbo.SEM_CLIENT.COMPUTER_ID = dbo.SEM_COMPUTER.COMPUTER_ID
AND dbo.SEM_COMPUTER.COMPUTER_ID = dbo.SEM_AGENT.COMPUTER_ID
AND [IP_ADDR1_TEXT] = '$k'"
$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)
do{
try{
$rdr = $cmd.ExecuteReader()
# Read Computer Name, Computer ID, IP address, Domain, and Operating System from the Database into a multidimensional array
while ($rdr.read()){
$sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1), $rdr.GetValue(2), $rdr.GetValue(3), $rdr.GetValue(4), $rdr.GetValue(5), $rdr.GetValue(6), $rdr.GetValue(7), $rdr.GetValue(8))
}
$transactionComplete = $true
}
catch{
$transactionComplete = $false
}
}until ($transactionComplete)
}
Write-host $sql_output
$conn.Close()
你有没有考虑为建设循环中的SQL连接?另外,如果写入$ sql_output时出错,您将永远运行。对于故障排除,我会写$ host来保证文本是正确的,然后花时间确保您正确使用读写器。 – websch01ar
谢谢@ websch01ar你的解决方案的作品! – Glowie
我已将评论添加为答案。如果你不介意,是否只是SQL连接? – websch01ar