PowerShell - Loop Through Nested Objects I'm writing a PowerShell script to loop through an organization's PowerBI workspaces and spit out the report IDs, names, and URLs for each workspace - so, a nested loop.

Here's my working script thus far:

Install-Module -Name MicrosoftPowerBIMgmt

$myArray = @()

Login-PowerBIServiceAccount
Get-PowerBIWorkspace -Scope Organization | ForEach-Object { 
        $ws = $_
        Get-PowerBIReport -WorkspaceId $_.Id | ForEach-Object {
            $x = [pscustomobject]@{
                workspaceId = $ws.Id
                workspaceName = $ws.Name
                reportId = $_.id
                reportName = $_.Name
                reportUrl = $_.WebUrl
             }
        $myArray += $x
        }
}

$myArray | Export-Csv "PowerBIWorkspaceReports.csv"


Four questions:

1) Is there a better way to add the module dependency at the top? I can't find any info on how PowerBI looks for existing module dependencies.

2) Are the ForEach-Object calls redundant? I see in simple code people assume whatever command runs after the pipe runs just fine whether on a single object or a collection of objects.

3) Is there a better way to manage my objects? Since I need data from the first loop ( the Workspace name and ID) and the second loop, is there an easier way to join them (or export them as a flattened list) than looping?

4) Should I just append my rows directly to the CSV? There doesn't seem to be the equivalent of While(File.Open() ...) in PowerShell.

And any other advice appreciated.
I rejigged your code a little to make it tidier. I don't have PowerBI, so I haven't tested it, and I can't guarantee that I haven't done anything dumb.

I got rid of the nested loop. Note the -PipelineVariable ws. What that does is put the output of that stage of the pipeline into a variable called $ws, which we can refer to later. It means that we don't need to do $ws = $_.

-PipelineVariable is one of the "Common Parameters", and is available on many or most cmdlets. You can abbreviate it to -PV, by the way.

I also got rid of the intermediate array $myArray since it wasn't needed.

Install-Module -Name MicrosoftPowerBIMgmt

Login-PowerBIServiceAccount

Get-PowerBIWorkspace -Scope Organization -PipelineVariable ws | 
    ForEach-Object { Get-PowerBIReport -WorkspaceId $_.Id } | 
    ForEach-Object {
            [pscustomobject]@{
                workspaceId   = $ws.Id
                workspaceName = $ws.Name
                reportId      = $_.id
                reportName    = $_.Name
                reportUrl     = $_.WebUrl
             }
        } |
    Export-Csv "PowerBIWorkspaceReports.csv"