I am writing a powershell code with an SQL query to get information from one of our Databases and then put that information into a variable for further use. My entire code works, and does exactly what i want it to do.
But somewhere in this snippet of the code two errors are produced that I can't figure out why happen if the script is actually doing what it's supposed to do.
$Server = "######"
$Database = "######"
$UserSqlQuery = "SELECT [UdstyrsId]
,[Model]
,[Serienr]
,[Udlevdato]
,[Repnr]
,[Notat]
FROM [IT-Support].[dbo].[Udstyrsoplysninger] where aflevdato is null and repnr = $repnr"
function ExecuteSqlQuery($Server, $Database, $UserSQLQuery)
{
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';integrated security=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $UserSQLQuery
$Reader = $Command.ExecuteReader();
$Datatable.Load($Reader);
$Connection.Close()
return $Datatable
}
$ResultsDataTable = New-Object System.Data.DataTable
$ResultsDataTable = ExecuteSqlQuery $Server $Database $UserSqlQuery
Error code:
Exception calling "ExecuteReader" with "0" argument(s): "Incorrect syntax near '='."
At C:\Users\adm-#######\Desktop\UserResignation.ps1:70 char:13
+ $Reader = $Command.ExecuteReader();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Exception calling "Load" with "1" argument(s): "Value cannot be null.
Parameter name: dataReader"
At C:\Users\adm-#######\Desktop\UserResignation.ps1:71 char:13
+ $Datatable.Load($Reader);
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Line 70 and 71 is these lines in the script:
$Reader = $Command.ExecuteReader();
$Datatable.Load($Reader);
$repnr? Seems like your$UserSqlQueryhas syntax error because your where condition missing value.$Readerin the$Datatable.Load($Reader)? Btw. you can omit the;at the end with powershell.$repnris null or empty.