开发者

How to pass the parameter in SQL query from PowerShell

I have this code in PowerShell, that executes SQL query to UPDATE my table:

$Connection=new-object data.sqlclient.sqlconnection "server=server;database=mydb;trusted_connection=true;"
$Connection.open()

For ( $i = 0; $i -le $ActID.Length; $i ++ ) { 
    $cmd = New-Object System.Data.SqlClient.SqlCommand
    $cmd.Connection = $Connection
    $cmd.CommandText = 
    "
    update Table 
    set Note = @PATH
    "
    $cmd.Parameters.Add("@PATH", $ActID[$i].Values) | Out-Null

    $cmd.ExecuteNonQuery()
}

I tried to update the table with the variable defined in this string:

$cmd.Parameters.Add("@PATH", $ActID[$i].Values) | Out-Null

But when I execute the script the error log says that there is no value passed in $ActID[$i]

Are there other methods to pass parameters (variables) in po开发者_如何学Cwershell queries?


What could be the mistake:

$i -le $ActID.Length;

it should be probably

$i -lt $ActID.Length;

You could also use piping which simplifies the code:

$actId | % { ..... $cmd.Parameters.Add("@PATH", $_.Values) | Out-Null .... }

Besides that the property you use is Values - is it really what you wanted? Values looks like a collection of something. Maybe you wanted to use a single value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜