【问题标题】:Powershell single quote all array elements in parameters before SQL EXECPowershell在SQL EXEC之前单引号参数中的所有数组元素
【发布时间】:2020-12-01 03:14:58
【问题描述】:

我有下面的代码 sn-p 并且一切正常,只是看起来没有一个值被包含在存储过程给出的单引号中。

有没有办法告诉它在执行 SQL 之前将 $p 中的每个元素用单引号括起来?

$p 包含 30 个不同的元素,可以是数字或字母数字。

Param (
    [Parameter(Mandatory=$true)][array]$p
)
Process {
    $conn = New-Object System.Data.SqlClient.SqlConnection
    $conn.ConnectionString = "Data Source=OurServer;Initial Catalog=OurDatabase;Integrated Security=true"

    $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.Connection = $conn
    $cmd.CommandTimeout = 0
    $cmd.CommandText = "EXEC sp_test $p"
}

【问题讨论】:

  • 请考虑使用$cmd.Parameters$cmd.CommandType = "StoredProcedure",避免引用问题和可能的SQL 注入。

标签: sql-server powershell stored-procedures


【解决方案1】:

有许多选项可以更新数组元素:

# Using -replace
$p = $p -replace '^.*$','''$&'''

# Using foreach-object and string format operator
$p = $p | Foreach-Object { "'{0}'" -f $_ }

# Using foreach method
$p = $p.foreach({"'$_'"})

【讨论】:

  • 这里唯一的问题是,如果值为空,则仅在您期望 '' 作为第一个选项时添加一个单引号,例如 '
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 2016-02-12
  • 1970-01-01
  • 2020-06-19
  • 2017-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多