How to pass parameter in SQL query from PowerShell

I have this code in PowerShell that executes an SQL query for an 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 am trying to update a table with the variable defined in this row:

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

But when I try to execute the script, the error log says that in $ ActID [$ i]

no value

Are there other methods for passing parameters (variables) in powershell requests?

+1
source share
1 answer

What could be a mistake:

$i -le $ActID.Length;

he should probably be

$i -lt $ActID.Length;

You can also use a pipeline that simplifies the code:

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

, Values - , ? -. , .

+1

Source: https://habr.com/ru/post/1527924/


All Articles