在 Powershell 中使用 SqlClient 找不到接受参数“+”错误的位置参数

A positional parameter cannot be found that accepts argument '+' error using SqlClient in Powershell

我在 Azure 上运行手册的 powershell 脚本中遇到错误:

Write-Error : A positional parameter cannot be found that accepts argument '+'.
At Test-Update-IndexesForallShardsFromShardManagerRunbook:61 char:61
+ 
    + CategoryInfo          : InvalidArgument: (:) [Write-Error], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteErrorCommand

根据我在 Azure 自动化帐户上看到的来自 运行 作业的日志,我在以下代码中的某处查明了我的脚本中错误的来源:

$updateStatisticSql = "UPDATE STATISTICS [$Using:tableName] ( [$Using:statName] );"
$CmdUpdateStats=new-object system.Data.SqlClient.SqlCommand($updateStatisticSql, $Conn1)
$CmdUpdateStats.CommandTimeout=1500

Try
{
    $Ds=New-Object system.Data.DataSet
    $Da=New-Object system.Data.SqlClient.SqlDataAdapter($CmdUpdateStats)
    [void]$Da.fill($Ds)
}
Catch
{
    # Will catch the exception here so other statistics can be processed.
    Write-Error "Statistic " + $tableName + "(" + $statName + ") could not be updated. Investigate the statistic."
}

似乎在每行之后添加了日志记录之后,它在 "fill" 函数之后没有记录,所以我假设那里出了问题。但是我没有看到错误和这个函数之间的关系。它似乎也不是脚本中断错误,因为它永远不会进入捕获状态并且其余脚本运行良好。我还验证了统计信息已更新,即使我收到错误。

所以您看到的错误是因为您正在尝试使用连接构建字符串,这意味着您有空格,并且空格用于在调用 cmdlet 时分隔参数。将所有连接放入括号中:

Write-Error ("Statistic " + $tableName + "(" + $statName + ") could not be updated. Investigate the statistic.")