views:

254

answers:

1

I have this code in PowerShell, that executes SQL query for UPDATE 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 try to update table with variable defined in this string:

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

But when i try to execute script, error log says that there is no value passed in $ActID[$i]

Is there other methods to pass parameters (variables) in powershell queries?

A: 

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.

stej
@Zshava - also beware you don't have a WHERE clause on that query - I don't know if that was your intention or not...
thedugas
@thedugas - good point.
stej
@thedugas - it was my intention, my true query is more complex but it is not important in this qestion
Zshava