Home > database >  PowerShell, PSCustomObject, array format issue
PowerShell, PSCustomObject, array format issue

Time:12-26

I am trying to create array made by PSCustomObject elements, but having some issues with it. Here is the simplified example of the code I have:

$FineData = @()

foreach ($Session in $Sessions) {  

        $Job = Get-VBRTaskSession -Session $Session 

        $Result = [pscustomobject]@{ 

                Id = $job.Id.Guid                       
        }

        $FineData  = $Result
}

$FineData

The format it returns:

Id                                                                                                                                                                                                                            
{19ea68a7-f2c3-4429-bc46-a87b4a295105, 3ebf8568-10ce-4608-bbb2-c80d06874173, 2ec28852-3f5e-477d-8742-872863e41b6d}                                                                                                             

The format I want:

Id             : 19ea68a7-f2c3-4429-bc46-a87b4a295105

Id             : 3ebf8568-10ce-4608-bbb2-c80d06874173

Id             : 2ec28852-3f5e-477d-8742-872863e41b6d

Thanks in advance.

CodePudding user response:

It seems like your Get-VBRTaskSession could be returning more than one object, hence an inner loop is required:

$FineData = foreach ($Session in $Sessions) {  
    foreach($guid in (Get-VBRTaskSession -Session $Session).Id.Guid) {
        [pscustomobject]@{ 
            Id = $guid
        }
    }
}

$FineData

You can then pipe $FineData to Format-List if you want it to be displayed as a list in your console:

$FineData | Format-List

As aside, adding to a fixed collection should be avoided, see this answer for details: Why should I avoid using the increase assignment operator ( =) to create a collection.

  • Related