Reputation: 17
I have sample Json format that I am currently trying to code using powershell and convert it to Json format using PScustomobject, however I am having a hard time since the DBdetails count will depend on an array that I am retrieving. What is wrong with my logic?
$dbcountall = 1
foreach ($alldblist in $dblist)
{
if($dbcountall -eq 1)
{
$name = $alldblist.name
$dbdetailsname = "DBDetails" + $dbcountall
$dbpiece = [pscustomobject]@{
SourceType = "$name"
TargetType = "$name"
}
$alldb += [pscustomobject]@{
DataBasesCount = $dblist.count
$dbdetailsname = $dbpiece
}
}
else
{
$name = $alldblist.name
$dbdetailsname = "DBDetails" + $dbcountall
$dbpiece = [pscustomobject]@{
SourceType = "$name"
TargetType = "$name"
}
$alldb += [pscustomobject]@{
$dbdetailsname = $dbpiece
}
}
$dbcountall++
}
##Output is
"Databases": [
{
"DatabasesCount": "4",
"DBDetails1": {
"Source": "SampleDB1",
"Target": "SampleDB1"
}
},
{
"DBDetails2": {
"Source": "SampleDB2",
"Target": "SampleDB2"
}
},
{
"DBDetails3": {
"Source": "testdatabase",
"Target": "testdatabase"
}
},
{
"DBDetails4": {
"Source": "Testdatabase_backup_10GB",
"Target": "Testdatabase_backup_10GB"
}
}
],
Result should look like this and from above, its having an additional bracketing.
"Databases": [
{
"DatabasesCount": "3",
"DBDetails1": {
"Source": "db1",
"Target": "db1"
},
"DBDetails2": {
"Source": "db2",
"Target": "db2"
},
"DBDetails3": {
"Source": "db3",
"Target": "db3"
}
}
],
Upvotes: 0
Views: 1883
Reputation: 36297
Instead of creating one object per database, create one object, then add properties for each database.
$DatabaseInfo = [pscustomobject]@{
DatabasesCount = $dblist.count
}
For($i=1;$i -le $dblist.count;$i++){
$DBObject = [pscustomobject]@{
Source = $dblist[$i-1].Name
Target = $dblist[$i-1].Name
}
$DatabaseInfo | Add-Member "DBDetails$i" $DBObject
}
Upvotes: 2