views:

168

answers:

1

I use Write-Host analyze objects, but some times it is hard to understand what the object actually is.

Consider:

Write-Host $null
Write-Host @()
Write-Host @($null, $null)

Prints:

# Actually it prints nothing

I would like some thing like this:

Null
@()
@(Null, Null)

Any suggestions?

+1  A: 

You can write a function that does the pretty-printing for you. Something like the following might work for your needs:

function pp($a) {
    if ($a -eq $null) {
        return "Null"
    } elseif ($a -is [object[]]) {
        $b = @()
        foreach ($x in $a) {
            $b += (pp $x)
        }
        $s = "@(" + [string]::Join(",", $b) + ")"
        return $s
    } else {
        return $a
    }
}

This has, however still problems with an empty array on the shell (works fine from a .ps1 file, though). Also Hashtables aren't supported, but nested arrays are. Probably still needs some plumbing but might give a general direction.

The @($null, $null) array seems to be an ugly beast, resisting even comparing it to $null. Weird.

Joey
Couldn't you add something like if ($a.length -eq 0) {write-host "@()"}
aphoria
It worked already from my test script, that's what puzzles me. I tested @(), @(1,2), @(1,@(2,3)), $null and @($null,$null). Only the last one came out as "Null", the others worked like they should. But seemingly this is not the case when using the function directly from the commandline. But sure, go ahead and modify to your liking.
Joey
Sorry, I misread your answer and didn't try your code. Your code does works for me from the shell with an empty array.
aphoria