我目前正在研究在PowerShell中调用ReST请求的用例。 POST请求的主体是动态创建的,从CSV文件中读取数据。
以下是我的最终请求正文
的方式{
"@type": "mtTaskParameter",
"name": "$src_sfdc$",
"type": "EXTENDED_SOURCE",
"sourceConnectionId":"00002E0B00000000000C"
},
{
"@type": "mtTaskParameter",
"name": "$tgt_db_del$",
"type": "TARGET",
"targetConnectionId":"00002E0B00000000000D"
},
{
"@type": "mtTaskParameter",
"name": "$tgt_db_ups$",
"type": "TARGET",
"targetConnectionId":"00002E0B00000000000D"
},
{
"@type": "mtTaskParameter",
"name": "$tgt_status$",
"type": "TARGET",
"targetConnectionId":"00002E0B00000000000D"
}
}
目前我的实施方式如下
if($connectionParameterized -eq "true"){
$str = @"
"@type": "mtTaskParameter",
"name": "$name",
"type": "$type"
"@
if($type -eq "SOURCE"){
$sourceConnectionId = <get source id>
$str = $str+
@"
,"sourceConnectionId":"$sourceConnectionId"
"@
}
if($type -eq "TARGET"){
$targetConnectionId = <get target id>
$str = $str+
@"
,"targetConnectionId":"$targetConnectionId"
"@
}
$finalstr = $finalstr+@"
{
$str
},
"@
}
这很好用,但代码变得非常混乱,难以扩展。同时在打印时,格式不合适。
有没有更好的方法来解决这个问题?
注意:从示例中可以看出,请求正文包含几个特殊字符,如@,$ etc。
答案 0 :(得分:1)
如果您包含CSV,这会更容易,但基本上,您可以将CSV作为对象数组导入,然后将其转换为JSON。
您可以通过添加自定义成员来自定义通过导入CSV创建的对象,以便转换为JSON为您提供所需的输出。
您还可以根据特定条件对对象数组进行分组或过滤,以制作不同的对象。
这里有一些示例代码可能不会直接起作用,但应该在某种程度上展示这个概念:
$json = Import-Csv -Path C:\my\data.csv |
ForEach-Object -Process {
$row = $_
$propName = $row.Type.ToLower() + 'ConnectionId'
$row | Add-Member -NotePropertyName $propName -NotePropertyValue $out["$mapping_name"].$name -Force -PassThru
} |
ConvertTo-Json