我正在使用以下代碼在 PowerShell 中迭代 JSON 物件
$awsFileResponse = '{
"commitId":"opb274750f582ik",
"blobId":"io6956a1a967243514e194lk54b86",
"filePath":"PowershellScript.ps1",
"fileMode":"NORMAL",
"fileSize":5755,
"fileContent":"7"
}'
foreach($KeyParam in $awsFileResponse)
{
Write-Host 'Ashish'
Write-Host $KeyParam
Write-Host $KeyParam.NAME
Write-Host $KeyParam.VALUE
if($KeyParam.NAME -eq 'fileContent')
{
$fileContentResponse = $KeyParam.VALUE
Write-Host $fileContentResponse
}
}
我沒有得到我正在尋找的確切輸出。
- 它不會為以下幾行列印任何內容 Write-Host $KeyParam Write-Host $KeyParam.NAME Write-Host $KeyParam.VALUE
- 如果條件允許,它不會進入內部
uj5u.com熱心網友回復:
它不起作用,因為變數 awsFileResponse 不是 Json 物件而是字串。因此,首先您必須將字串決議為自定義物件。然后你必須回圈它里面的所有屬性。并檢查 $keeyParam.NAME 而不是 $keyParam 物件的 fileContent 鍵條件。
作業代碼
$awsFileResponse = '{
"commitId":"7cf4ca8ea129c2b9b274750f58245605e081580e",
"blobId":"1d46ec453a6956a1a967243514e1944754c54b86",
"filePath":"PowershellScript.ps1",
"fileMode":"NORMAL",
"fileSize":5755,
"fileContent":"7"
}'
#Parse to Json Object
$jsonObject = $awsFileResponse | ConvertFrom-Json;
#loop all custom object properties
foreach($KeyParam in $jsonObject.psobject.properties)
{
Write-Host 'Ashish'
Write-Host $KeyParam
Write-Host $KeyParam.NAME
Write-Host $KeyParam.VALUE
if($KeyParam.NAME -eq 'fileContent')
{
$fileContentResponse = $KeyParam.VALUE
Write-Host $fileContentResponse
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389629.html
上一篇:在條件運算式中重新拋出例外
