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