1

I am using an object to get value of RestAPI url details which contains the assets. The location is the region where the assets are present.

I am reading the location values using import-csv menthod and using a for loop

$inventory = Import-Csv "File.csv"

$output = foreach($i in $inventory){
    $RestAPIobject = Invoke-RestMethod -Method Get -uri "XXXXXXXXXXXXXXXXXXX"

    $CBObject = New-Object -TypeName psobject

    $CBObject | Add-Member -MemberType NoteProperty -Name Region-Value $i.region
    $CBObject | Add-Member -MemberType NoteProperty -Name Assets -Value $RestAPIobject.name
    
    $CBObject
}

I am getting the output as :-

Location  Assets                                                                                                                       
Region1   {H1, H2, H3}
Region2   {A1, A2}   

whereas I want the output as

Location  Assets                                                                                                                          
Region1   H1
Region1   H2
Region1   H3
Region2   A1
Region2   A2
1
  • Your code outputs a CB member, but the output lists a Assets column instead. Is this the real code you are running? Commented Jan 31, 2022 at 12:46

1 Answer 1

1

Based on the output, it appears that $RestAPIobject.name contains multiple values.

Change your code to:

$inventory = Import-Csv "File.csv"

$output = foreach($i in $inventory){
    $RestAPIobject = Invoke-RestMethod -Method Get -uri "XXXXXXXXXXXXXXXXXXX"

    foreach($name in $RestAPIobject.name){
        $CBObject = New-Object -TypeName psobject
        $CBObject | Add-Member -MemberType NoteProperty -Name Location -Value $i.location
        $CBObject | Add-Member -MemberType NoteProperty -Name CB -Value $name
    
        $CBObject
    }
}

Unless you intend for your script to be working with PowerShell 2.0, I'd recommend using the [PSCustomObject] object initializer syntax (introduced in Windows PowerShell 3.0):

foreach($name in $RestAPIobject.name){
    [PSCustomObject]@{
        Location = $i.location
        CB       = $name
    }
}

Much simpler syntax and a bit faster than New-Object + Add-Member

Sign up to request clarification or add additional context in comments.

4 Comments

No I am using Powershell 5.1
@DishantDhokia Then the [PSCustomObject]@{...} syntax will work perfectly fine for you
How will u add more values in output if RestAPIobject has many objects id name status details as teh current for loop will only have name
@DishantDhokia If $RestAPIobject is an array: foreach($object in $RestAPIobject){ [pscustomobject]@{ Name = $object.name; ID = $object.id <# and so on ... #>}}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.