Reputation: 302
so I have an object
$appstatus=[pscustomobject] @{
txtlist=@()
csvlist=@()
someotherproperties
}
and a function which either loads TXT or imports CSV file. Depending on the filename chosen it fills in one property of $appstatus object. Then I have another function to show currently loaded list. Something like
function showhosts(){
if(($appstatus.txtlist).count -gt 0){
write-host $appstatus.txtlist
}else{
write-host $appstatus.csvlist
}
}
txtlist is fine, but the problem is with csvlist because write-host does not show the nice table format but this @{property=value; ...} long string instead. I cannot just type $appstatus.csvlist without write-host, because that would NOT be displayed and become return value of a function instead, so how can I display the object nicely from within a function the same way as if it was called from the main script?
Upvotes: 1
Views: 1777
Reputation: 25001
The requirements are as follows:
You can utilize Out-Host for this purpose.
function showhosts(){
if(($appstatus.txtlist).count -gt 0){
$appstatus.txtlist | Out-Host
}else{
$appstatus.csvlist | Out-Host
}
}
Write-Host does not output to the success stream by default and has more robust capability when printing to the console. As of PowerShell 5, it writes to the information stream, which can be stored in a variable and accessed later. The information stream can be redirected as well to the success stream if you wanted to capture its output with typical variable assignment. However, it does stringify the output to the console, which explains the @{property = value}
syntax. Any [string]
cast arrays are then joined by a single space on most systems since that is the default separator.
# Example 1
# Stringify simple array
Write-Host 1,2,3
1 2 3
# Example 2
# Stringify an array of custom objects
Write-Host $obj.two
@{property=value1} @{property=value2}
# Example 3
# Saving Write-Host output to variable $out using information stream
Write-Host $obj.two -InformationVariable out
@{property=value1} @{property=value2}
$out
@{property=value1} @{property=value2}
# Redirecting information stream to success stream
# Notice write-host no longer outputs to console after redirection
# $out has normal output plus write-host output
$out = "first line`n"
$out += Write-Host $obj.two 6>&1
$out
first line
@{property=value1} @{property=value2}
Upvotes: 2