Search code examples
powershellazureazure-sql-databaseazure-automation

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


I am getting an error in my powershell script for a runbook on Azure:

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

Based on the logs I see on my Azure autmation account from a job that ran, I pinpointed the origin of the error in my script somewhere in the following code:

$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."
}

It seems after adding logging after each line, that it doesn't log after the "fill" function, so I assume something is going wrong there. But I am not seeing the relation between the error and this function. It also doesn't seem a script breaking error, since it never goes into the catch and the rest of the scripts runs fine. I also validated that the statistics are updated, even though the error I am getting.


Solution

  • So the error you are seeing is because you are trying to build a string using concatenation which means you have spaces and spaces are used to delimit parameters when calling cmdlets. Put all the concatenation into parens:

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