I have a function Get-Projects
that returns an array of objects. I want to print these to the console so the user can select which project they are interested in. However, I have four scenarios only two of which print the desired/expected result.
Scenario 1 - Tabular Output, No Function
When I simply "return" the projects like so they are printed out as expected in tabular fashion. This is the desired format.
$projects = Get-Projects
$projects
# Console Output
id name children
-- ---- --------
1 Project 1 1 {@id=2; name=Project 2}
3 Project 3 3 {@id=4; name=Project 4}
Scenario Two - No Output w/ Write-Projects Function
I created a function named Write-Projects
to encapsulate the formatting behavior in case I decide to change how the formatting down the road. Yet, when I do this nothing is printed to the console.
Function Write-Projects
{
Param([Object[]] $projects)
$projects
}
$projects = Get-Projects
Write-Projects $projects
# No Console Output
Scenario 3 - String Output w/ Write-Projects Function
If I modify Write-Projects to use Write-Host $projects
I do get console output but not what I expected. It's appears to be the string representation of my Object array.
Function Write-Projects
{
Param([Object[]] $projects)
Write-Host $projects
}
$projects = Get-Projects
Write-Projects $projects
# Console Output
@{id=1; name=Project 1; children=System.Object[]} @{id=2; name=Project 2; children=System.Object[]}
Scenario 4 - Tabular Output w/ Write-Projects Function
I discovered this question which solves the problem but I am uncertain why. Essentially my Write-Projects method now looks like this.
Function Write-Projects
{
Param([Object[]] $projects)
Write-Host ($projects | Format-Table | Out-String)
}
$projects = Get-Projects
Write-Projects $projects
# Console Output
id name children
-- ---- --------
1 Project 1 1 {@id=2; name=Project 2}
3 Project 3 3 {@id=4; name=Project 4}
What is happening in each of these scenarios and why I am getting the output as described?