使用csv变量的Powershell SQL Select语句

时间:2018-01-30 22:27:48

标签: sql-server powershell

在下面的代码中,我尝试使用从csv引入的变量来查询具有多个select语句的数据库,并使用读取器加载数据表。

代码运行时没有错误,但不检索任何数据。

$csv = Import-Csv $filepath

$database = "DBNAME"
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=True;"

$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString

$connection.Open()

$sqlCommand = $connection.CreateCommand()
$Datatable = New-Object System.Data.DataTable

ForEach ($row in $csv){

   $query = "Select Emailaddress,Column2 from Users Where [Emailaddress] = '$row.Email'"

   $sqlCommand.CommandText = $query
   $DataReader = $sqlCommand.ExecuteReader()  
   $DataTable.Load($DataReader)

}


$DataTable | export-csv "c:\Output\Seereader.csv" -NoTypeInformation
$connection.Close()

2 个答案:

答案 0 :(得分:0)

此:

$query = "Select Emailaddress,Column2 from Users Where [Emailaddress] = '$row.Email'"

应该是这样的:

$query = "Select Emailaddress,Column2 from Users Where [Emailaddress] = '$($row.Email)'"

答案 1 :(得分:0)

虽然之前的答案有效,但它很容易受到 SQL注入

Obligatory xkcd

xkcd: Explots of a Mom - xkcd.com

如果您不确定" SQL注入"是;它只是一个非常有价值的谷歌......

即。你真的需要去找出来!

正确的方法......

参数化您的查询!

# Your query; with a @param
$Query = "SELECT Emailaddress, Column2 FROM [Users] WHERE [Emailaddress] = @emailAddress";

# Set up your basic command
$command = $connection.CreateCommand()
$command.CommandText = $Query

# Fill in the parameters!
$command.Parameters.AddWithValue("@emailAddress", $row.Email)

# Run boy, run!
$results = $command.ExecuteReader()

# Resultification (that's definitely not a made up word)
$table = New-Object System.Data.DataTable
$table.Load($results)    

安全无声:-)