使用here-string和variable扩展的PowerShell SQL查询

时间:2015-10-31 23:42:28

标签: sql powershell

如何合并swSaturday = 1swSunday = 1服务器的查询结果[RebootTime]可能是swSunBeginTimeswSatBeginTime,也可能无效我只是尝试在文本文件中的计算机列表上运行此查询。

收到的错误为Exception calling "Fill" with "1" argument(s): "Incorrect syntax near the keyword 'WHERE'.",如果删除了WHERE swName = $($props.Server),则错误就会消失。

Function GetServer-RebootLookUp{

Begin{
 $servers = GC D:\Scripts\reboots1.txt
 $SQLServer = 'Server101'
 $Database = 'Database101'
 $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
 $SqlConnection.ConnectionString = "Server = $SQLServer; Database = $Database; Integrated Security = True"
}#End Begin

Process{
 $servers | ForEach-Object{
 $props = @{}
 $props.Server = $_

 $ServerQuery = @"
SELECT swName AS [Server], swRack AS [Rack], swEnvironment AS [Environment], swSunBeginTime AS [RebootTime], swSchedule as [Schedule]
FROM SW_SERVICE_LVL
INNER JOIN SW_SPECIALTY
 ON swDiscount = swSpecialtyId
AND swEnvironment IN ( 'Cert', 'Test', 'Prod' )
AND swSchedule IN ( 'SCCM - Monthly' )
AND swGrpResp = 'MyGroup'
AND swRootObjectType = 'Server'
WHERE swSunday = 1
WHERE swName = $($props.Server)
 "@
 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
 $SqlCmd.CommandText = $ServerQuery
 $SqlCmd.Connection = $SqlConnection
 $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
 $SqlAdapter.SelectCommand = $SqlCmd
 $DataSet = New-Object System.Data.DataSet
 $SqlAdapter.Fill($DataSet)
 $DataSet.Tables[0]
}
}#end process

End{
 $SqlConnection.Close()
}
}#End function!
GetServer-RebootLookUp

1 个答案:

答案 0 :(得分:0)

您的查询有两个WHERE子句。这不是有效的SQL。

改变这个:

WHERE swSunday = 1
WHERE swName = $($props.Server)

对此:

WHERE swSunday = 1
    AND swName = $($props.Server)