2015-10-31 46 views
0

PowerShell的SQL查詢如何可以結合查詢結果是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 
+0

我不知道,如果你只是需要一些報價? 'WHERE swName ='$($ props.Server)'' – Matt

+0

哎呦忘了補充一點,我試了一下,得到了同樣的異常。我必須將這裏的字符串更改爲「@」,這樣變量纔會擴展,而不是通常使用的「@」。 – user4317867

+0

如果您鍵入來自$($ props.Server)的靜態字符串, '''WHERE swName = comp1' – Matt

回答

0

您的查詢有兩個WHERE子句。這不是有效的SQL。

更改此:

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

要這樣:

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

奇怪的是,這樣做使查詢循環以某種方式。 – user4317867