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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

@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 - it was my intention, my true query is more complex but it is not important in this qestion
This does not work, it basically took @PATH literally as what I was trying to insert.
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))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.