Azure Function PowerShell写入Azure表存储仅插入一行问题排查
问题排查:Azure Function PowerShell脚本无法向表存储追加多行数据
我帮你找出问题的根源了——你的LogToAzureTable函数里的文件写入逻辑是覆盖模式,导致第一条日志被第二条完全覆盖了。
具体原因
每次调用LogToAzureTable时,你用Out-File $outputTable写入JSON实体,但Out-File默认是覆盖写入(未启用-Append参数)。第一次写入"test log 1"的JSON内容后,第二次调用函数时,新的JSON直接替换了之前的内容,所以最终只有最后一条日志被传到表存储。
另外,函数里的$outputTable.done其实是多余的,Azure Function运行时会自动处理输出绑定的文件内容,不需要手动调用这个方法。
修复后的脚本
把Out-File命令加上-Append参数改成追加写入模式,同时去掉不必要的$outputTable.done:
$requestBody = Get-Content $req -Raw | ConvertFrom-Json $name = $requestBody.name # GET method: each querystring parameter is its own variable if ($req_query_name) { $name = $req_query_name } function LogToAzureTable( $log ) { $time = Get-Date -Format O $entity = [PSObject]@{ PartitionKey = $EXECUTION_CONTEXT_INVOCATIONID RowKey = "PID($PID): ($time)" LogContent = $log } # 加上-Append参数实现追加写入 $entity | ConvertTo-Json | Out-File $outputTable -Append } Out-File -Encoding Ascii -FilePath $res -inputObject "Hello $name" LogToAzureTable "test log 1" LogToAzureTable "test log 201"
额外说明
Azure Function的表存储输出绑定支持从文件中读取多个JSON实体(每个实体单独占一行即可),用追加模式写入后,每个日志实体都会被单独识别并插入到表存储中,这样两条日志就能都成功插入了。
内容的提问来源于stack exchange,提问作者woody2k
相关产品推荐
相关产品推荐

