私はpowershellを初めて使用し、まだ慣れていません。サーバーの一部をリアルタイムでリモート化しようとしています。そのために、JSON 形式でデータを送信する RestAPI を使用します (Powershell は自動的に PSCustomObject に変換します)。
問題は、JSON/data API にフィールド タイムスタンプがないため、追加する必要があったことです。残念ながら、powershell の JSON ツールは限定されているようで、直接追加することはできませんでした。タイムスタンプと呼ばれる新しい PSCustomObject を作成し、それを API からのデータと組み合わせる必要がありました。
残念ながら、データは正しく解析されません。文字列、文字列の配列、ハッシュテーブルを調べます。最悪でした。最後に、今作業しようとしている JSON.NET Framework をダウンロードしました...
だからここにメインコード部分があります:
Function Combine-Objects {
Param (
[Parameter(mandatory=$true)]$Object1,
[Parameter(mandatory=$true)]$Object2
)
$arguments = [Pscustomobject]@()
foreach ( $Property in $Object1.psobject.Properties){
$arguments += @{$Property.Name = $Property.value}
}
foreach ( $Property in $Object2.psobject.Properties){
$arguments += @{ $Property.Name= $Property.value}
}
$Object3 = [Pscustomobject]$arguments
return $Object3
}
while (1)
{
$startpoint = "REST API URL"
$endpoint = "POWER BI API URL"
$response = Invoke-RestMethod -Method Get -Uri $startpoint
$timestamp=get-date -format yyyy-MM-ddTHH:mm:ss.fffZ
$response2 = [PsCustomObject]@{"timestamp"=$timestamp}
$response3 = Combine-Objects -Object1 $response -Object2 $response2
Invoke-RestMethod -Method Post -Uri "$endpoint" -Body (ConvertTo-Json @($response3))
}
PSCustomObject を結合する前に、次のものがあります。
total : 8589463552
available : 5146566656
percent : 40,1
used : 3442896896
free : 5146566656
変換後に正しいJSONが得られました
[
{
"total": 8589463552,
"available": 5146566656,
"percent": 40.1,
"used": 3442896896,
"free": 5146566656
}
]
タイムスタンプを結合して追加した後、次のようになります。
Name Value
---- -----
total 8589463552
available 5146566656
percent 40,1
used 3442896896
free 5146566656
timestamp 2019-10-09T22:17:18.734Z
変換後に私に与えたもの:
[
{
"total": 8589463552
},
{
"available": 5146566656
},
{
"percent": 40.1
},
{
"used": 3442896896
},
{
"free": 5146566656
},
{
"timestamp": "2019-10-09T22:17:18.734Z"
}
]
私が欲しかったのは単純なものだけでしたが:
[
{
"total" :98.6,
"available" :98.6,
"percent" :98.6,
"used" :98.6,
"free" :98.6,
"timestamp" :"2019-10-11T09:21:04.981Z"
}
]