1

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 powershell queries?

Dale K
  • 25,246
  • 15
  • 42
  • 71

1 Answers1

2

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
  • 28,745
  • 11
  • 71
  • 104
  • 1
    @Zshava - also beware you don't have a WHERE clause on that query - I don't know if that was your intention or not... – dugas Feb 15 '10 at 16:55
  • @thedugas - it was my intention, my true query is more complex but it is not important in this qestion –  Feb 16 '10 at 07:21
  • This does not work, it basically took @PATH literally as what I was trying to insert. – Nathan McKaskle Jun 26 '17 at 19:41
  • Good point re `-lt` vs. `-le`, but I think the `Parameters.Add()` call (which you've taken from the question) won't work. The docs suggest that you must use something like: `$cmd.Parameters.Add([System.Data.SqlClient.SqlParameter]::new("PATH", $_.Values))` – mklement0 Dec 15 '22 at 20:16