Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using custom object to get values + Powershell

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 :-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading